I have a forumla that adds items togther in a shopping cart, I use:
Code:
var div2 = document.getElementById("cost");
var num2 = document.getElementById('cost').innerHTML;
div2.innerHTML = "Total of: £"+(parseFloat(num2.replace(/_/g, '.').match(/[0-9\.]+/g))+parseFloat(idstoof.replace(/_/g, '.').match(/[0-9\.]+/g)));
num2 is the current total and idstoof is the item that has been added, so it adds it to the total, however if I add, an item worth 59.95 3 times it gives me a total of:
£179.85000000000002
however is there a way to make it only go to 2 charecters past the decimal place?
1. math operations between floated numbers are somehow tricky. As the CPU uses binary to calculate, some decimal floated numbers become irational or periodical when translated into binary, thus they are rounded. In some cases this sequence: decimal -> binary -> calculate -> binary -> decimal might add those small approximations over the tolerance, thus a strange result might occur:
Code:
<script type="text/javascript">
var x=0.8
var y=0.1
var xy=x*y;
alert(xy) // will display, surprisingly, 0.08000000000000002
</script>
Surprisingly for humans, as we are used to see the world of numbers mainly in a decimal key.
The good news is that "error" appears only when you display the results not when the CPU "stores" them, so that the calculation itself is accurate. But what to do for a correct display? There are several ways to by pass that problem. One of them is working with integers:
Code:
var x=0.8
var y=0.1
var xy=((x*10)*(y*10))/(10*10)
alert(xy) // display 0.08
But in practice, as we hardly need a precision over 3 floated points, we may use rounded methods, thus here's the following issue:
2. toFixed(num) method will round a number at a certain precision (number of decimals)
Code:
var x=0.8
var y=0.1
var xy=(x*y).toFixed(2);
alert(xy) // display 0.08
Bookmarks