tags:

views:

102

answers:

7
+1  Q: 

result of the sum

Why 9.1 + 3.3 is not 12.4 ?

<script>

  alert( 9.1 + 3.3 )

</script>

result: 12.399999999

...and how should I sum it?

+1  A: 

This is a floating point error, where the variable cannot store the value precisely. If you are only working to one decimal place, then you could multiply all of your figures by 10 to do calculations as this will keep all the numbers as integers and you shouldn't get the problem you are seeing. Obviously when displaying the number you will have to divide it by 10.

ar
+2  A: 

That's come from floating point number precision. This problem comes with every programming language and is caused by the fact that a real number can have an unlimited number of digits. So it is always given with a precision.

You can try: Number(9.1+3.3).toPrecision(3)

luc
I need the integer value... Number(9+3).toPrecision(3) result: 12.0
Leo
A: 

Interesting that by swapping the values you get the correct outcome !

thelost
A: 

The cause is the floating point number. You can have a method to round off the number to desired places after the decimal.

<script language="javascript">

function formatNumber(myNum, numOfDec)
{
var decimal = 1
for(i=1; i<=numOfDec;i++)
decimal = decimal *10

var myFormattedNum = (Math.round(myNum * decimal)/decimal).toFixed(numOfDec)
return(myFormattedNum)
}
</script> 
Kangkan
A: 

Use Math.round function to round up the values.

alert(Math.round(9.1+3.3));

pavun_cool
+3  A: 

Try

alert((9.1 + 3.3).toFixed(1));

The toFixed() method formats a number to use a specified number of trailing decimals.

The number is rounded up, and nulls are added after the decimal point (if needed), to create the desired decimal length.

Pandiya Chendur
I need the integer value... alert((9 + 3).toFixed(1)); result: 12.0
Leo
+2  A: 

It´s the IEEE 754 legacy ghost of JavaScript haunting you and every other JavaScript developer.

Have a look at Crockford´s presentation and you´ll get a better understanding

And as to how: you should make your decimals into integers by multipliying them and in the end turn them back to decimals.

anddoutoi
indeed: `(9.1*10 + 3.3*10)/10 = 12.4`
Sam Hasler
Great presentation, the bit about IEEE 754 is about 15 minutes in if anyone wants to skip straight to that.
Sam Hasler