Issue with rounding mode in ROUND_UP in Java

I want to use ROUND_UP as the rounding mode. But, when the decimals in the original number are less than three decimals, then at the end "1" is appended.

  int precision = 3;
  double[] values = { 1.9024999999999999, 2.1234, 2.2835, 2.04 };
  for (double value : values) {
     BigDecimal bd1 = new BigDecimal(value);
     bd1 = bd1.setScale(precision, BigDecimal.ROUND_UP);
     System.out.println(value + "===========" + bd1.doubleValue());
  }

The output is as below -

1.9024999999999999===========1.903

2.1234===========2.124

2.2835===========2.284

2.04===========2.041
Jon Skeet
people
quotationmark

But, when the decimals in the original number is less than 3 decimals, then at the end "1" is appended.

Your value of 2.04 isn't really 2.04. It's actually 2.04000000000000003552713678800500929355621337890625, which is the double value closest to 2.04. So when you round that up, it's being correctly rounded up to 2.041.

You're using the BigDecimal(double) constructor, which almost certainly doesn't do what you want it to - see the documentation for warnings about it. If you use BigDecimal.valueOf(double) instead, it will behave as you expect.

Code:

import java.math.BigDecimal;

public class Test {
    public static void main(String[] args) {
        int precision = 3;
        double[] values = { 1.9024999999999999, 2.1234, 2.2835, 2.04 };
        for (double value : values) {
            BigDecimal bd1 = BigDecimal.valueOf(value);
            bd1 = bd1.setScale(precision, BigDecimal.ROUND_UP);
            System.out.println(value + "===========" + bd1.doubleValue());
        }
    }
}

Output:

1.9024999999999999===========1.903
2.1234===========2.124
2.2835===========2.284
2.04===========2.04

people

See more on this question at Stackoverflow