Java BigDecimal.round ()

I am trying to round a BigDecimal value to the nearest 1000 using the code below

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 is great for the above input. result below

Old ------> 791232

New ------> 792000

But the code does not work for input <1,00,000 (e.g. 79123) and input> 10,000,000 (e.g. 7912354)

Actual and Expected Result

Another point noted that if we change the accuracy from 3 to 2, as shown below

new MathContext(2,RoundingMode.UP)

then it works for input <1.00.000.

Please, help

+4
source share
6 answers

You can also update your code:

BigDecimal newValue = oldValue.round(new MathContext(oldValue.precision() - 3,
                        RoundingMode.CEILING));
+1
source

No need to divide / multiply by 1000, you just forgot to set the scale

oldValue.setScale(0, RoundingMode.UP);

:

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());

:

------- 79123

------- 79200

------- 7912113

------- 7920000

+5

1000, RoundingMode.UP,

.

RoundingMode.HALF_UP, :

" ", , .

ΦXocę 웃 epeúpa..

.

+1

, .

1.2345 3 1,23

1000, ;

  • 1000
  • 1000
0

MathContext precision (.. ). , setScale ; , 10 - -3 1000. , , 1000 ( 1000), RoundingMode.HALF_UP ( RoundingMode.HALF_EVEN, ):

    BigDecimal b = new BigDecimal("7725232");
    b = b.setScale(-3, RoundingMode.HALF_UP);
    System.out.println(b.intValue());
0

Your accuracy is responsible for the number of digits on the left side of your number. Therefore, to fix this, take the total length and subtract the expected accuracy.

Final code:

BigDecimal oldValue = new BigDecimal("77252");
int expectedPrecision = 3;
int length = oldValue.precision() - expectedPrecision;

BigDecimal newValue=oldValue.round(new MathContext(length, RoundingMode.UP));

System.out.println("Old -------   "+oldValue.intValue());
System.out.println("New-------   "+newValue.intValue());
0
source

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


All Articles