As I execute the following code snippet
public static void main(String args[]) {
BigDecimal one = new BigDecimal(1);
BigDecimal two = new BigDecimal(2);
BigDecimal three = new BigDecimal(3);
System.out.println(one.divide(two));
System.out.println(one.divide(three));
}
The console showed:
0.5
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)
at gov.nta.fms.web.rest.Fms421rResource.main(Fms421rResource.java:204)
Why one.divide(two) is working fine? But failed to execute one.divide(three) ?
Root Cause
Because I am not specifying a precision and a rounding-mode.
BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, so it cannot be able to show me the exact representation of the number.
We need to assign its scale and rounding mode, please check the following code snippets:
public static void main(String args[]) {
BigDecimal one = new BigDecimal(1);
BigDecimal two = new BigDecimal(2);
BigDecimal three = new BigDecimal(3);
System.out.println(one.divide(two));
System.out.println(one.divide(three, 2, BigDecimal.ROUND_HALF_UP));
}
Here is java doc:
divide
public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
Returns aBigDecimalwhose value is(this / divisor), and whose scale is as specified. If rounding must be performed to generate a result with the specified scale, the specified rounding mode is applied.The newdivide(BigDecimal, int, RoundingMode)method should be used in preference to this legacy method.- Parameters:
divisor- value by which thisBigDecimalis to be divided.scale- scale of theBigDecimalquotient to be returned.roundingMode- rounding mode to apply.- Returns:
this / divisor- Throws:
ArithmeticException- ifdivisoris zero,roundingMode==ROUND_UNNECESSARYand the specified scale is insufficient to represent the result of the division exactly.IllegalArgumentException- ifroundingModedoes not represent a valid rounding mode.- See Also:
ROUND_UP,ROUND_DOWN,ROUND_CEILING,ROUND_FLOOR,ROUND_HALF_UP,ROUND_HALF_DOWN,ROUND_HALF_EVEN,ROUND_UNNECESSARY
0.5
0.33
Reference
[1] http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divide(java.math.BigDecimal,%20int,%20int)
No comments:
Post a Comment