大量错误地在Javascript中舍入

大量错误地在Javascript中舍入

本文介绍了大量错误地在Javascript中舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅以下代码:

 < html> 
< head>

< script src =http://www.json.org/json2.jstype =text / javascript>< / script>

< script type =text / javascript>

var jsonString ='{id:714341252076979033,type:FUZZY}';
var jsonParsed = JSON.parse(jsonString);
console.log(jsonString,jsonParsed);


< / script>
< / head>
< body>
< / body>
< / html>

当我在Firefox 3.5中看到我的控制台时,jsonParsed的值为:

  Object id = 714341252076979100 type = FUZZY 

即数字是四舍五入的。尝试不同的价值观,相同的结果(数字四舍五入)。

我也没有得到它的舍入规则。 714341252076979136四舍五入到714341252076979200,而714341252076979135四舍五入到714341252076979100。编辑:看到下面的第一条评论。显然这不是关于JSON,而是关于Javascript数字处理。但是问题仍然存在:



为什么会发生这种情况?

解决方案

你在这里看到的实际上是两个圆角的影响。 ECMAScript中的数字在内部表示为双精度浮点数。当 id 设置为 714341252076979033 0x9e9d9958274c359 ,它实际上被分配了最接近的可表示的双精度值,即 714341252076979072 0x9e9d9958274c380 )。当你打印出这个值时,它被四舍五入为十五位十进制数字,它给出 14341252076979100


See this code:

<html>
<head>

<script src="http://www.json.org/json2.js" type="text/javascript"></script>

<script type="text/javascript">

    var jsonString = '{"id":714341252076979033,"type":"FUZZY"}';
    var jsonParsed = JSON.parse(jsonString);
    console.log(jsonString, jsonParsed);


</script>
</head>
<body>
</body>
</html>

When I see my console in Firefox 3.5, the value of jsonParsed is:

Object id=714341252076979100 type=FUZZY

I.e the number is rounded. Tried different values, the same outcome (number rounded).

I also don't get its rounding rules. 714341252076979136 is rounded to 714341252076979200, whereas 714341252076979135 is rounded to 714341252076979100.

EDIT: see first comment below. Apparently this is not about JSON, but something about Javascript number handling. But the question remains:

Why is this happening?

解决方案

What you're seeing here is actually the effect of two roundings. Numbers in ECMAScript are internally represented double-precision floating-point. When id is set to 714341252076979033 (0x9e9d9958274c359 in hex), it actually is assigned the nearest representable double-precision value, which is 714341252076979072 (0x9e9d9958274c380). When you print out the value, it is being rounded to 15 significant decimal digits, which gives 14341252076979100.

这篇关于大量错误地在Javascript中舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:35