JavaScript - painless decimal multiplication
JavaScript has a bug when multiplying decimals, try yourself:
0.1 * 0.2
> 0.020000000000000004 // NodeJS 0.8
The way to correct this is to multiply the decimals before multiple their values, try yourself:
( 0.1 * 10 + 0.2 * 10 ) / 10
> 0.3
You can create a function for this:
function multdec ( val1, val2 ) {
return ( val1 * 10 + val2 * 10 ) / 10;
}
You can extend the Math object:
Math.multdec = function ( val1, val2 ) {
return ( val1 * 10 + val2 * 10 ) / 10;
}
Now you can call this operation in two ways:
multdec( val1, val2 ); // 0.3
// or
Math.multdec ( val1, val2 ); // 0.3Written by Mariz Melo
Related protips
4 Responses
Thanks for sharing!
The is not really a bug, but a side effect of JavaScript using floating point numbers.
But its still a nice solution to the issue.
more info about floating point numbers here.
http://floating-point-gui.de/formats/fp/
You're adding decimals together, not multiplying them.
For multiplication the code would need to change to:
return ( (val1 * 10) * (val2 * 10) ) / 100;
return ( (12.12 * 10) * (100 * 10) ) / 100;
will give '1211.999999999998'
Where as
return (12.12*100)
will give '1212'
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside