设置双精度至小数点后6位的精度

时间:2018-11-27 09:07:00

标签: java precision number-formatting

我想将双精度值格式化为6位精度而不舍入。

格式后的期望值到小数点后6位

20790123833965.960938

我尝试使用十进制格式

   DecimalFormat formatter = new DecimalFormat("#0.000000");
   System.out.println(formatter.format(hashValue) );

我知道了

20790123833965.960000

2 个答案:

答案 0 :(得分:10)

正如@Benoit在评论中已经说过的,要保持数字的全精度,您需要BigDecimal

BigDecimal hashValue = new BigDecimal("20790123833965.960938");
DecimalFormat formatter = new DecimalFormat("#0.000000");
System.out.println(formatter.format(hashValue));

输出:

  

20790123833965.960938

答案 1 :(得分:0)

使用此代码,它将起作用。

public class JavaFormatter {
    public static void main(String args[]) {
        BigDecimal hashValue = new BigDecimal("20790123833965.960938");     
        DecimalFormat formatter = new DecimalFormat("#.######");
        System.out.println(formatter.format(hashValue));
    }
}