Search code examples
javamathdoubledecimal

Java - unexpected result when rounding a double/float to 2 decimals


I encounter a problem when round a double to 2 decimals. I know this questions have been asked in many places. But my question is slightly different and I cannot find it in other places.

So far as I know, there are 2 ways to do this.

  1. Math.round(double*100.0)/100.0
  2. DecimalFormat(“###.##”)

I am trying to use the first way: a custom way to round double. When the second decimal is 0, the result will only print the first decimal and ignore the second one.

For example,

  1. Math.round(1.23333*100.0)/100.0 The result is 1.23. This works good.
  2. Math.round(3.90*100.0)/100.0. The result is 3.9. Problem occurs. I want to show 3.90 instead of 3.9
  3. Math.round(3*100.0)/100.0. The result is 4.0. I want 4.00 instead of 4.0

So, my question is that how I can have a double value with 2 decimals no matter if the last decimal is 0 or not. I know I can use the second way- DecimalFormat(“###.##”) to achieve what I want! But is it possible to do it by using the first way?

Edit: Thanks for the answers. It looks like it is NOT possible to use the round() method to achieve it. However, some people suggest to use the combination of 2 ways to achieve it. But I think using only DecimalFormat(“###.##”) can get what I want. Can anyone confirm it?


Solution

  • Have you tried the following?

    DecimalFormat(“###.00”)
    

    If not mistaken, trailing zeros are left blank when using the #-sign.