开发者

result of the sum

开发者 https://www.devze.com 2022-12-21 12:30 出处:网络
Why 9.1 + 3.3 is not 12.4 ? <script> alert( 9.1 + 3.3 ) </script> result: 12.399999999 ...and how shoul开发者_运维问答d I sum it?This is a floating point error, where the variable ca

Why 9.1 + 3.3 is not 12.4 ?

<script>

  alert( 9.1 + 3.3 )

</script>

result: 12.399999999

...and how shoul开发者_运维问答d I sum it?


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.


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)


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.


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.


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


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> 


Use Math.round function to round up the values.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消