JavaScript: Problematic Decimal Calculations
by sjmcpherson
HTML
<div id="elm"></div>
JavaScript
var elm = document.getElementById("elm");
//JavaScript problematic decimal calculations, when working with decimal values(e.g currency) between 0 & 1 use .toFixed();
var sum1 = 0.1 + 0.2;
elm.innerHTML = "<p>"+sum1+"</p>";
var sum2 = 0.4 * 0.2;
elm.innerHTML += "<p>"+sum2+"</p>";
var sum3 = 0.7 - 0.3;
elm.innerHTML += "<p>"+sum3+"</p>";
elm.innerHTML += "<p>"+sum3.toFixed(2)+"</p>"; //Rounding For Currency
elm.innerHTML += "<p>"+parseFloat(sum3.toFixed(2))+"</p>"; //Rounding & Removing Trailing '0's
elm.innerHTML += "<p>"+parseFloat(parseFloat(sum3).toFixed(2))+"</p>"; //Insure a Float with Rounding & Removing Trailing '0's
elm.innerHTML += "<p>"+Math.round(sum3*1000)/1000 + "</p>"; //Alternative way for rounding
elm.innerHTML += "<p>"+parseInt('30px')+"</p>";//Will remove the 'px'because of type coersion