Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal.round()

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)

Actual and Expected Result

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

like image 893
Jijo Mathew Avatar asked Jan 05 '23 07:01

Jijo Mathew


1 Answers

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

like image 101
ΦXocę 웃 Пepeúpa ツ Avatar answered Jan 15 '23 15:01

ΦXocę 웃 Пepeúpa ツ