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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With