Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal: Round to the nearest whole value

I need the following results

100.12 -> 100.00 100.44 -> 100.00 100.50 -> 101.00 100.75 -> 101.00 

.round() or .setScale() ? How do I go about this?

like image 332
n a Avatar asked Nov 09 '10 13:11

n a


People also ask

How do I round off BigDecimal value?

math. BigDecimal. round(MathContext m) is an inbuilt method in Java that returns a BigDecimal value rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place.

What is rounding mode in BigDecimal Java?

Description. The java. math. BigDecimal. setScale(int newScale, RoundingMode roundingMode) returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.

How do I Ceil BigDecimal in Java?

use the Math. ceil() function. The method ceil gives the smallest integer that is greater than or equal to the argument.

How do you find the whole number in BigDecimal?

intValue() is an in-built function which converts this BigDecimal to an integer value. This function discards any fractional part of this BigDecimal. If the result of the conversion is too big to be represented as an integer value, the function returns only the lower-order 32 bits.


1 Answers

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.HALF_UP); System.out.println(value + " -> " + scaled); 

Using round() is a bit more involved as it requires you to specify the number of digits to be retained. In your examples this would be 3, but this is not valid for all values:

BigDecimal rounded = value.round(new MathContext(3, RoundingMode.HALF_UP)); System.out.println(value + " -> " + rounded); 

(Note that BigDecimal objects are immutable; both setScale and round will return a new object.)

like image 80
Grodriguez Avatar answered Sep 29 '22 11:09

Grodriguez