/ toFixed

Quickie: JavaScript decimal multiplication

Another oddity of JavaScript I found. Multiplying decimal numbers can be tricky (or malicious?).

Order of numbers can matter in multiplication.

// order #1
135*1.15*10.5
// = 1630.125

// order #2
1.15 * 10.5 * 135
// = 1630.125

// order #3
10.5 * 1.15 * 135
// = 1630.125

// order #4
10.5 * 135 * 1.15
// = 1630.1249999999998

This can be bad, if you want to round to 2 decimals. For example in financial operations.

(10.5 * 135 * 1.15).toFixed(2)
// "1630.12"

(10.5 * 1.15 * 135).toFixed(2)
// "1630.13"

Boom! One cent difference.
The solution can be adding a pretty small number to the product. For example 0.000001.

(10.5 * 135 * 1.15 + 1e-6).toFixed(2)
// "1630.13"

(10.5 * 1.15 * 135 + 1e-6).toFixed(2)
// "1630.13"

Tags:
#js #decimal #math #multiplication #toFixed #round

TvK

IT and languages. Feel free to be a grammar-nazi and correct my English (or any other language).

Read More