Home  >  Article  >  Web Front-end  >  javascript中的float运算精度实例分析_javascript技巧

javascript中的float运算精度实例分析_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:20:491208browse

有人问到一个js问题:

复制代码 代码如下:

var i = 0.07;
var r = i*100;
alert(r);

结果为什么是7.0000000000000001?
查了下资料,其实我们知道JavsScript中,变量在存储时并不区分number和float类型,而是统一按float存储。而javascript使用IEEE 754-2008 标准定义的64bit浮点格式存储number,按照IEEE 754的定义: http://en.wikipedia.org/wiki/IEEE_754-2008
decimal64对应的整形部分长度为10,小数部分长度为16,所以默认的计算结果为“7.0000000000000001”,如最后一个小数为0,则取1作为有效数字标志。

类似地,我们可以想像,1/3的结果应该是0.3333333333333333。
那么如何校正这个值呢?
可以用以下方法:
一、parseInt

var r4=parseInt(i*100);

二、Math.round

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

以上两种方法都可以得到7
附全部测试代码:
复制代码 代码如下:



测试脚本





Statement:
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