开发者

Rounding off a double to 3 digit decimal place but zero at 3rd decimal place disappears in java

开发者 https://www.devze.com 2023-01-17 16:38 出处:网络
I want to round of my double to 3 decimal places in java. I don\'t want to trim off t开发者_C百科he zero. So if my double is 2.34, I still want it as 2.340.DecimalFormat myFormatter = new DecimalFor

I want to round of my double to 3 decimal places in java.

I don't want to trim off t开发者_C百科he zero. So if my double is 2.34, I still want it as 2.340.


DecimalFormat myFormatter = new DecimalFormat("0.000");
String output = myFormatter.format(2.34d);


String res = String.format("%.3f", 2.34);

or if you want to print

System.out.printf( "%.3f",2.34);


Use the following decimal format: 0.000


use setMinimumFractionDigits and setRoundingMode

    final DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(3);
    df.setRoundingMode(RoundingMode.HALF_UP);
    df.format(2.34);


Following on from Tony Ennis's comment, you can't round a floating-point variable to a specific number of decimal places, or digits, without converting it into base-10. That's what the answers above are doing, and they are also converting it into displayable text.

0

精彩评论

暂无评论...
验证码 换一张
取 消