I am trying to round a BigDecimal value to the nearest 1000 using the below code
BigDecimal oldValue = new BigDecimal("791232");
BigDecimal newValue=oldValue.round(new MathContext(3,
RoundingMode.UP));
System.out.println("Old ------- "+oldValue.intValue());
System.out.println("New------- "+newValue.intValue());
This works fine for the above input. the result is below
Old------>791232
New------>792000
But the code not working for input < 1,00,000 (e.g 79123) and input > 10,00,000 (e.g 7912354)
One more point noticed that if we change the precision from 3 to 2 as below
new MathContext(2,RoundingMode.UP)
then it is working for input < 1,00,000.
Please help
No need to divide/multiply by 1000, You just forgot to set the scale
oldValue.setScale(0, RoundingMode.UP);
after that the code is working as you wish:
BigDecimal oldValue = new BigDecimal("79123");
oldValue = oldValue.setScale(0, RoundingMode.UP);
BigDecimal newValue = oldValue.round(new MathContext(3, RoundingMode.UP));
System.out.println("Old ------- " + oldValue.intValue());
System.out.println("New------- " + newValue.intValue());
the output:
Old ------- 79123
New------- 79200
and
Old ------- 7912113
New------- 7920000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With