I am writing a web app that is converting SQL data in the form of text (dollar amounts) to numbers, then totalling. However, I've come across only certain values that round very oddly!
I have a JSFiddle to show this (with more values than below) as well as sample code below, using text vars as I would be pulling from SQL data. JSFiddle found here
I've done what I've seen recommended here by various people and multiplied values by 100 to work with integers only - hoping to avoid rounding issues. I've tried various combinations of Number() and toFixed etc but can't seem to get a handle on the best way to avoid rounding issues in JS. Most values are fine, but I accidentally came across '129.42' being an issue. I have no idea what other numbers might also cause problems leaving my app totally unreliable!! This is very peculiar behaviour!?
HTML:
<html>
<body id='body'>
Example of NASTY rounding in JavaScript:
<br><br>
</body>
</html>
JS:
var ary = [ '129.42', '129.45', '125.42', '125.45', '130.42'];
var div;
for (var x in ary) {
var text = ary[x];
var num = parseInt(Number(text)*100);
div = document.createElement('div');
div.innerHTML = 'Original "text" number: '+text;
document.getElementById('body').appendChild(div);
div = document.createElement('div');
div.innerHTML = 'Multiply by 100 and Converted to Integer: '+num+'<br><br>';
document.getElementById('body').appendChild(div);
}
The above results in:
Example of NASTY rounding in JavaScript:
Original "text" number: 129.42 Multiply by 100 and Converted to Integer: 12941
Original "text" number: 129.45 Multiply by 100 and Converted to Integer: 12944
Original "text" number: 125.42 Multiply by 100 and Converted to Integer: 12542
Original "text" number: 125.45 Multiply by 100 and Converted to Integer: 12545
Original "text" number: 130.42 Multiply by 100 and Converted to Integer: 13041