Someone asked a js question:
var i = 0.07;
var r = i*100;
alert(r);
Why is the result 7.000000000000000000001?
After checking the information, we actually know that in JavaScript, variables do not distinguish between number and float types when storing, but store them uniformly according to float. JavaScript uses the 64bit floating point format defined by the IEEE 754-2008 standard to store number, according to the definition of IEEE 754: /wiki/IEEE_754-2008
The length of the shaping part corresponding to decimal64 is 10 and the length of the decimal part is 16, so the default calculation result is "7.00000000000000001". If the last decimal is 0, 1 will be taken as the valid number mark.
Similarly, we can imagine that the result of 1/3 should be 0.333333333333333333333333333.
So how to correct this value?
The following methods can be used:
1. parseInt
var r4=parseInt(i*100);
two,
var r2=((i*100)*1000)/1000;
Both of the above methods can get 7
All test codes are attached:
<html>
<head>
<title>Test script</title>
<script language="JAVASCRIPT">
function init()
{
var i = 0.07;
var r = i*100;
var r2=((i*100)*1000)/1000;
var r3 = eval(i*100);
var r4=parseInt(i*100);
var r5=parseFloat(i*100*1.0000);
var r6=(1/3);
alert(r);
alert("="+r2);
alert("eval="+r3);
alert("parseInt="+r4);
alert("parseFloat="+r5);
alert(""+r6);
}
</script>
</head>
<body onload="init();">
</body>
</html>
Copy the codeThe code is as follows:
var i = 0.07;
var r = i*100;
alert(r);
Why is the result 7.000000000000000000001?
After checking the information, we actually know that in JavaScript, variables do not distinguish between number and float types when storing, but store them uniformly according to float. JavaScript uses the 64bit floating point format defined by the IEEE 754-2008 standard to store number, according to the definition of IEEE 754: /wiki/IEEE_754-2008
The length of the shaping part corresponding to decimal64 is 10 and the length of the decimal part is 16, so the default calculation result is "7.00000000000000001". If the last decimal is 0, 1 will be taken as the valid number mark.
Similarly, we can imagine that the result of 1/3 should be 0.333333333333333333333333333.
So how to correct this value?
The following methods can be used:
1. parseInt
var r4=parseInt(i*100);
two,
var r2=((i*100)*1000)/1000;
Both of the above methods can get 7
All test codes are attached:
Copy the codeThe code is as follows:
<html>
<head>
<title>Test script</title>
<script language="JAVASCRIPT">
function init()
{
var i = 0.07;
var r = i*100;
var r2=((i*100)*1000)/1000;
var r3 = eval(i*100);
var r4=parseInt(i*100);
var r5=parseFloat(i*100*1.0000);
var r6=(1/3);
alert(r);
alert("="+r2);
alert("eval="+r3);
alert("parseInt="+r4);
alert("parseFloat="+r5);
alert(""+r6);
}
</script>
</head>
<body onload="init();">
</body>
</html>