Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding necessary with BigDecimal numbers

I want to set scale of two BigDecimal numbers a and b . as in this example :

BigDecimal a = new BigDecimal("2.6E-1095");         BigDecimal b = new BigDecimal("2.7E-1105");         int i = 112, j=1;          BigDecimal aa = a.setScale(i+j);         BigDecimal bb = b.setScale(i+j); 

and when i run i have this exception:

java.lang.ArithmeticException: Rounding necessary     at java.math.BigDecimal.divideAndRound(BigDecimal.java:1439)     at java.math.BigDecimal.setScale(BigDecimal.java:2394)     at java.math.BigDecimal.setScale(BigDecimal.java:2437) 

Why rounding is necessary ? if i don't want to make around, what is solution please ?

Thanks

like image 740
Mehdi Avatar asked May 24 '12 08:05

Mehdi


People also ask

How do you round BigDecimal numbers?

You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded: BigDecimal scaled = value. setScale(0, RoundingMode.

How do I stop rounding in BigDecimal?

56 if you use BigDecimal newValue = myBigDecimal. setScale(2, RoundingMode. DOWN); " This statement is true for HALF_DOWN not for DOWN mode.

What is the default rounding mode in BigDecimal Java?

The default is HALF_UP, meaning that the rounding mode is to round toward the nearest neighbor unless both neighbors are equidistant, (and in this case, round toward the even neighbor).

Does BigDecimal have decimal places?

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.


1 Answers

You have two BigDecimal numbers both of which require over a 1000 decimal places. Trying to set the scale to only have 113 decimal places means you will lose precision and therefore you need to round.

You can use the setScale methods that take a RoundingMode to prevent the exception but not the rounding.

like image 179
brain Avatar answered Sep 30 '22 14:09

brain