How to change doubles in Java by two digits

I am trying to fill (not a round!) Doubles to two digits in a Java application. I use DecimalFormat for this, but noticed that for negative values โ€‹โ€‹close to zero, the values โ€‹โ€‹are not rounded to -0.01 , but to -0.00 .

 public class MyTest { void formatAndPrint(double value) { DecimalFormat df = new DecimalFormat("0.00"); df.setRoundingMode(RoundingMode.FLOOR); System.out.println(value + " => " + df.format(value)); } @Test public void testFloor() { formatAndPrint(2.3289); // 2.32 formatAndPrint(2.3); // 2.30 formatAndPrint(-1.172); // -1.18 formatAndPrint(0.001); // 0.00 formatAndPrint(0.0001); // 0.00 formatAndPrint(-0.001); // -0.01 formatAndPrint(-0.0001); // -0.00 WRONG, expected: -0.01 } } 

Other solutions, such as Math.floor(value * 100.0) / 100.0 , do not have this problem, but have other problems, for example, erroneous flooring 2.3 to 2.29 .

Is there a flooring solution for Java that works in all cases?

+5
source share
1 answer

The BigDecimal implementation is working fine.

 BigDecimal value = new BigDecimal(-0.0001); value = value.setScale(2, BigDecimal.ROUND_FLOOR); System.out.println(value.toPlainString()); 

Output: -0.01

2.3 will still take up to 2.29 . This is not the result of flooring, but the result of recording 2.3 as a double. The closest 64-bit representation of IEEE754 2.3 is 2.29999...

When creating an instance of BigDecimal, you can instead provide a string of type new BigDecimal("2.3") , which will not lead to such errors.

+7
source

Source: https://habr.com/ru/post/1276157/


All Articles