请问:在Java语言中如何把一个浮点数精确到小数点后的某几位?

在Java语言中输出一个浮点数,它会给出默认的小数。我现在要求精确到小数点后的某几位怎么办?如下面的一道题目,求a=1/1! 1/2! 1/3! ...... 1/n!且a精确到小数点后5位。详细一点。

-- Math.round()
(double) (Math.round(sd3*10000)/10000.0); 

这样为保持4位 

(double) (Math.round(sd3*100)/100.0); 

这样为保持2位.

-- BigDecimal
//保留小数点后两位小数
public double Number2(double pDouble)
{
  BigDecimal  bd=new  BigDecimal(pDouble);
  BigDecimal  bd1=bd.setScale(2,bd.ROUND_HALF_UP);
  pDouble=bd1.doubleValue();
  long  ll = Double.doubleToLongBits(pDouble);
  
  return pDouble;
}
格式化输出数字

-- NumberFormat
--java.text 包中的一些包可以处理这类问题。下面的简单范例使用那些类解决上面提出的问题:
    import java.text.NumberFormat;
    import java.util.Locale;
    public class DecimalFormat1 {
        public static void main(String args[]) {
            // 得到本地的缺省格式
            NumberFormat nf1 = NumberFormat.getInstance();
            System.out.println(nf1.format(1234.56));
            // 得到德国的格式
            NumberFormat nf2 =
                NumberFormat.getInstance(Locale.GERMAN);
            System.out.println(nf2.format(1234.56));
        }
    }

-- DecimalFormat
    import java.text.DecimalFormat;
    import java.util.Locale;
    public class DecimalFormat2 {
        public static void main(String args[]) {
            // 得到本地的缺省格式
            DecimalFormat df1 = new DecimalFormat("####.000");
            System.out.println(df1.format(1234.56));
            // 得到德国的格式
            Locale.setDefault(Locale.GERMAN);
            DecimalFormat df2 = new DecimalFormat("####.000");
            System.out.println(df2.format(1234.56));
        }
    }

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-12-06
1.(double) (Math.round(sd3*10000)/10000.0);

这样为保持4位

(double) (Math.round(sd3*100)/100.0);

这样为保持2位.

2.另一种办法
import java.text.DecimalFormat;

DecimalFormat df2 = new DecimalFormat("###.00");

DecimalFormat df2 = new DecimalFormat("###.000");

System.out.println(df2.format(doube_var));

第一个为2位,第二个为3位.本回答被网友采纳
第2个回答  2012-12-06
使用bigdecimal方法计算,这是最精确的
第3个回答  2012-12-06
float f=11.12356;
java.text.DecimalFormat df = new java.text.DecimalFormat("########.00");
df.format(f);
相似回答