[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
JavaScript

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

That’s all from the Gemba.