Java BigDecimal in Javascript

Elvis Ciotti
2 min readJan 30, 2024

--

To use Java’s BigDecimal operations like multiply, and divide, the closest library I found is bignumber.js

To make sure the logic is identical, I took some numbers from some prod data, and then compared the Java output to the Javascript output.

How to use those classes:

When working with those “big” classes, keep the values always inside, and to send and receive to them, always use string. Never get their double/number value or you risk operating on those and losing precision. If it’s not clear, read this.

Division

For various numbers I tested from 0.00000154 to 4.67381e-10, those two lines of code return the same results.

Java:


BigDecimal.ONE.divide(
new BigDecimal("inputNumber"), 8, RoundingMode.HALF_EVEN
).toString()

Javascript:

new BigNumber(1).dividedBy("inputNumber").toFixed(8).toString()

Multiplication

For numbers 649350.64935065, 0.0556933, 2139582054.04156352 multiplied by 0, or 0.00001 or 21228.58301, those two lines of code return identical values

Java:

 new BigDecimal("input").multiply("input2").setScale(3, RoundingMode.HALF_EVEN).toString()

Javascript:

new BigNumber("input")
.multipliedBy("input2")
.decimalPlaces(3, BigNumber.ROUND_HALF_EVEN);

The only difference in output: trailing zeroes

the only tiny difference I found is that Java BigDecimal adds trailing zeros (e.g. “0.0” or “0.000” instead of just zero) when calling toString() , while bignumber.js just returns “0”.

Overriding the class seems like an overkill, so you could apply this function to the values to just add trailing zeros to all values. In my case the BigDecimal is part of a Value object I have around (and I print to the rest endpoint) so I’ve just overridden the setter to return the toString() value with this function applied.

/**
*
* @param {string} amount
* @returns {string}
*/
export const addTrailingZeroIfMissing = (amount) => {
if (/^\d+$/.test(amount)) {
return `${amount}.0`;
}

return amount;
};

Clap if useful.

Follow me for more.

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet