When I try the below code I am getting 2 strange outputs
42.01 42.01
82.00 82.00
Is anyone sure about why this is happening ? and can it be resolved with the using the below RoundingMode for BigDecimal in java 7/8.
import java.math.*;
class HelloWorld {
public static void main(String[] args) {
BigDecimal hup = new BigDecimal(42.0050).setScale(2,
RoundingMode.HALF_UP);
BigDecimal hev = new BigDecimal(42.0050).setScale(2,
RoundingMode.HALF_EVEN);
BigDecimal hup2 = new BigDecimal(82.0050).setScale(2,
RoundingMode.HALF_UP);
BigDecimal hev2 = new BigDecimal(82.0050).setScale(2,
RoundingMode.HALF_EVEN);
System.out.println(hup);
System.out.println(hev);
System.out.println(hup2);
System.out.println(hev2);
}}
Thanks.
CodePudding user response:
That's a funny question.
Change your input to this and see the difference:
BigDecimal hup = new BigDecimal("42.0050").setScale(2,
RoundingMode.HALF_UP);
BigDecimal hev = new BigDecimal("42.0050").setScale(2,
RoundingMode.HALF_EVEN);
The result will be:
42.01 42.00
The problem, in reality, is how the input to BigDecimal is given.
In IntelliJ, for example, you see a warning when using BigDecimal not as String: