Example analysis of float operation precision in JavaScript _javascript skill

Source: Internet
Author: User
Tags eval
Someone asked a JS question:
Copy Code code as follows:

var i = 0.07;
var r = i*100;
Alert (R);

The result is 7.0000000000000001?
Check the data, in fact, we know that in Javsscript, variables are stored without distinguishing between number and float types, but uniformly by float storage. and JavaScript stores number in 64bit floating-point format defined by the IEEE 754-2008 standard, as defined by IEEE 754: http://en.wikipedia.org/wiki/IEEE_754-2008
Decimal64 the corresponding section length is 10, the decimal part length is 16, so the default result is "7.0000000000000001", if the last decimal is 0, then 1 is used as a valid digit mark.

Similarly, we can imagine that the 1/3 result should be 0.3333333333333333.
So how do you correct this value?
You can use the following methods:
First, parseint

var r4=parseint (i*100);

Second, Math.Round

var r2=math.round ((i*100) *1000)/1000;

Both of the above methods can be 7
Attach all test code:
Copy Code code as follows:

<title> Test Scripts </title>
<script language= "JAVASCRIPT" >
function init ()
{
var i = 0.07;
var r = i*100;
var r2=math.round ((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 ("math.round=" +R2);
Alert ("eval=" +R3);
Alert ("parseint=" +R4);
Alert ("parsefloat=" +R5);
Alert ("" +R6);
}
</script>
<body onload= "Init ();" >
</body>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.