[JavaScript] java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result
Tadashi Shigeoka · Tue, June 24, 2014
When I used the divide method to perform division with the bigdecimal.js npm module for calculating floating-point decimals in JavaScript, an error occurred.
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result
This seems to be an error that occurs when the result of division becomes a repeating decimal.
The solution is to specify the handling of repeating decimals in the second and third arguments of the divide method.
var bigdecimal = require("bigdecimal");
// (1) Example of error when division result becomes a repeating decimal
var one = new bigdecimal.BigDecimal(1);
var three = new bigdecimal.BigDecimal(3);
one.divide(three);
// java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result
// (2) Example of handling to avoid the error
// When rounding the division result to the 3rd decimal place, it would look like this
var HALF_UP = bigdecimal.RoundingMode.HALF_UP();
var result = one.divide(three, 2, HALF_UP);
result.floatValue();
// 0.33
It’s a bit cumbersome, but being able to handle values precisely is good.
Reference Information
- iriscouch/bigdecimal.js: Arbitrary-precision Javascript BigInteger and BigDecimal real numbers
- BigDecimal.divide() 使用時の注意 - 誰も見ませんように(・`ω・´) (`・ω´・)
- BigDecimalを使った割り算について - QA@IT
- Java BigDecimalで足し算, 引き算, 掛け算, 割り算そして四捨五入する方法 | ホームページ制作のサカエン(墨田区)
That’s all from the Gemba.