Formatting double to 2 decimals doesn't work

后端 未结 4 1201
旧时难觅i
旧时难觅i 2021-01-20 04:34

I want to round this double:

3.499999999999999

to:

3.50

And I already used these two methods:

<         


        
相关标签:
4条回答
  • 2021-01-20 05:04

    Did you try replacing the 0's with #'s?

    DecimalFormat df = new DecimalFormat("#.##"); System.out.println(df.format(input));

    According to here the # will be resolved to 0 if the digit is absent

    0 讨论(0)
  • 2021-01-20 05:08

    You can use the printf formatting which may be simpler.

    System.out.printf("%.2f%n", 3.5);
    

    prints

    3.50
    
    0 讨论(0)
  • 2021-01-20 05:09

    Your first solution is really, really close. Just do this:

        DecimalFormat df = new DecimalFormat("0.00");
        System.out.println(df.format(input));
    

    The reason your version doesn't work is that you're taking the input double, formatting it as a String with 2dp, but then converting it back to a double. System.out.println is then printing the double as it always would, with no special decimal-place rules.

    0 讨论(0)
  • 2021-01-20 05:16

    You can use Precision class of apache commons-math

    double result = Precision.round(3.499999999999999, 2);
    
    0 讨论(0)
提交回复
热议问题