Home > Backend Development > PHP Tutorial > javascript 定时器内累加小数后变成16位的浮点数,这是啥意思?

javascript 定时器内累加小数后变成16位的浮点数,这是啥意思?

WBOY
Release: 2016-06-06 20:20:50
Original
1523 people have browsed it

javascript 定时器内累加小数后变成16位的浮点数,这是啥意思?
请看这:

<code>var startNum = 1;
    setInterval(function ()
    {
        startNum += 0.1;
        console.log(startNum);
    }, 500);</code>
Copy after login
Copy after login

打印出来是这样的:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
1.6000000000000005

这难道是坑吗?郁闷。

回复内容:

javascript 定时器内累加小数后变成16位的浮点数,这是啥意思?
请看这:

<code>var startNum = 1;
    setInterval(function ()
    {
        startNum += 0.1;
        console.log(startNum);
    }, 500);</code>
Copy after login
Copy after login

打印出来是这样的:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
1.6000000000000005

这难道是坑吗?郁闷。

很正常,这是由于精确度造成的问题,不信你试一下0.1+0.2不等于0.3。

http://segmentfault.com/q/1010000000137297

看这个标准 http://www.baidu.com/link?url=ax1PkOuwwFU_KTyr29jOuhSr9v-i-Zg8fqAqty9Xbo_2oLAYg-_2CIIPeo3HKbXV3ohudDm6DKjK4rvzhGwao2rsRd7MF6QsEwQO9ShILXc1nIK3oHeI90MDFEyXBmtcTmhycPcznpwUvWH_emJzZ7IMNbn99fBEs8G4iphb32e&wd=&eqid=9ac65804000049bc00000005568e60b4

要利用编程语言计算小数的话最好先转换为整数计算

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template