Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding BigDecimal to *always* have two decimal places

I'm trying to round BigDecimal values up, to two decimal places.

I'm using

BigDecimal rounded = value.round(new MathContext(2, RoundingMode.CEILING));
logger.trace("rounded {} to {}", value, rounded);

but it doesn't do what I want consistently:

rounded 0.819 to 0.82
rounded 1.092 to 1.1
rounded 1.365 to 1.4 // should be 1.37
rounded 2.730 to 2.8 // should be 2.74
rounded 0.819 to 0.82

I don't care about significant digits, I just want two decimal places. How do I do this with BigDecimal? Or is there another class/library better suited to this?

like image 559
Brad Mace Avatar asked Oct 05 '22 07:10

Brad Mace


People also ask

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.

How do you round BigDecimal?

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.

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).

How do you round to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.


1 Answers

value = value.setScale(2, RoundingMode.CEILING)
like image 453
Louis Wasserman Avatar answered Oct 13 '22 21:10

Louis Wasserman