How to truncate a BigDecimal without rounding
Use either RoundingMode.DOWN or RoundingMode.FLOOR. BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);
Use either RoundingMode.DOWN or RoundingMode.FLOOR. BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);
IEEE 754 defines 1.0 / 0.0 as Infinity and -1.0 / 0.0 as -Infinity and 0.0 / 0.0 as NaN. By the way, floating point values also have -0.0 and so 1.0/ -0.0 is -Infinity. Integer arithmetic doesn’t have any of these values and throws an Exception instead. To check for all possible values (e.g. … Read more
In short, that’s the way it’s specified in the IEEE-754 standard, which is what Java’s Floating-Point Operations are based on. Why doesn’t division by zero (or overflow, or underflow) stop the program or trigger an error? Why does a standard on numbers include “not-a-number” (NaN)? The 754 model encourages robust programs. It is intended not … Read more
From the Java 11 BigDecimal docs: When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.) As a corollary of computing the exact … Read more