在 JavaScript 中错误地四舍五入的大数 [英] Large numbers erroneously rounded in JavaScript

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

问题描述

查看此代码:

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

当我在 Firefox 3.5 中看到我的控制台时,jsonParsed 的值是四舍五入的数字:

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

Object id=714341252076979100 type=FUZZY

尝试了不同的值,结果相同(数字四舍五入).

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

我也不明白它的四舍五入规则.714341252076979136 舍入为 714341252076979200,而 714341252076979135 舍入为 714341252076979100.

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

为什么会这样?

推荐答案

你在这里看到的其实是两个四舍五入的效果.ECMAScript 中的数字在内部表示为双精度浮点数.当 id 设置为 714341252076979033 (0x9e9d9958274c359 in hex)时,它实际上被分配了最接近的可表示双精度值,即 714341252076979072(0x9e9d9958274c380).当您打印出该值时,它会被四舍五入为 15 位有效的十进制数字,即 14341252076979100.

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 中错误地四舍五入的大数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆