Leo
Leo

Reputation: 1809

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?

Upvotes: 1

Views: 310

Answers (7)

ACP
ACP

Reputation: 35268

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.

Upvotes: 2

anddoutoi
anddoutoi

Reputation: 10111

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.

Upvotes: 2

Pavunkumar
Pavunkumar

Reputation: 5335

Use Math.round function to round up the values.

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

Upvotes: 1

Kangkan
Kangkan

Reputation: 15571

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> 

Upvotes: 0

thelost
thelost

Reputation: 6694

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

Upvotes: 0

luc
luc

Reputation: 43096

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)

Upvotes: 2

a&#39;r
a&#39;r

Reputation: 36999

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.

Upvotes: 2

Related Questions