3

I want to format a double value to 6 places precision without rounding.

expected value after format to 6 decimal places

20790123833965.960938

I have tried using decimal format

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

And i got this

20790123833965.960000
syafiqah
  • 391
  • 1
  • 6
  • 18
  • 1
    The result is reasonable, a `double` can only provide 15 to 16 decimal digits precision. – Henry Nov 27 '18 at 09:08
  • What's the input? – ernest_k Nov 27 '18 at 09:09
  • Related: [How to determine the max precision for double](https://stackoverflow.com/questions/36344758/how-to-determine-the-max-precision-for-double) – Ole V.V. Nov 27 '18 at 09:12
  • 2
    For extra precision, use `BigDecimal`: `BigDecimal hashValue = new BigDecimal("20790123833965.960938123");` Then it will produce the expected output. – Benoit Nov 27 '18 at 09:14
  • Was any of the answers helpful? If not, please tell ud what you’re still missing, we’re still here to help. If one was, please remember to accept the most helpful one. Thx. – Ole V.V. Nov 30 '18 at 19:07

2 Answers2

11

As @Benoit already said in a comment, to keep the full precision of your number, you need a BigDecimal:

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

Output:

20790123833965.960938

Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

Use this code, it will work.

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));
    }
}
Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
Java-Dev
  • 438
  • 4
  • 20