Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of java.math.MathContext

Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part.

From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online.

Please let me know if you have any idea on this.

like image 613
jatanp Avatar asked Aug 11 '08 05:08

jatanp


People also ask

What is MathContext DECIMAL32?

static MathContext. DECIMAL32. A MathContext object with a precision setting matching the IEEE 754R Decimal32 format, 7 digits, and a rounding mode of HALF_EVEN , the IEEE 754R default.

What is BigDecimal in Java?

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. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.

What is rounding mode in Bigdecimals Java?

The enum RoundingMode provides eight rounding modes: CEILING – rounds towards positive infinity. FLOOR – rounds towards negative infinity. UP – rounds away from zero. DOWN – rounds towards zero.

How do you multiply BigDecimal?

The multiply() method of java BigDecimal class is used to obtain a BigDecimal whose value is (this × multiplicand), and whose scale is (this. scale() + multiplicand. scale()) with rounding according to the context settings.


1 Answers

For rounding just the fractional part of a BigDecimal, check out the BigDecimal.setScale(int newScale, int roundingMode) method.

E.g. to change a number with three digits after the decimal point to one with two digits, and rounding up:

BigDecimal original = new BigDecimal("1.235"); BigDecimal scaled = original.setScale(2, BigDecimal.ROUND_HALF_UP); 

The result of this is a BigDecimal with the value 1.24 (because of the rounding up rule)

like image 126
Øystein Øvrebø Avatar answered Oct 08 '22 09:10

Øystein Øvrebø