1

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?

Leo
  • 1,583
  • 3
  • 16
  • 23
  • 1
    I'm pretty sure a question almost exactly like this was asked like 2 weeks ago. – animuson Mar 02 '10 at 09:51
  • 1
    Read this: http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary – codaddict Mar 02 '10 at 09:52
  • 2
    @animuson: It's a law of programming forums that this question gets asked once a week, and also the 3rd constant of life: death, taxes, and someone will complain about floating point math. – Noon Silk Mar 02 '10 at 09:59

7 Answers7

2

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.

a'r
  • 32,482
  • 7
  • 61
  • 65
2

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
  • 37,543
  • 21
  • 117
  • 168
2

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.

ACP
  • 32,884
  • 96
  • 217
  • 360
2

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
  • 9,289
  • 3
  • 27
  • 28
0

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

thelost
  • 6,351
  • 3
  • 24
  • 42
0

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
  • 13,787
  • 9
  • 64
  • 107
0

Use Math.round function to round up the values.

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

Pavunkumar
  • 4,717
  • 10
  • 39
  • 67