解析浮点数有舍入限制吗?我怎样才能解决这个问题? [英] Parse Float has a rounding limit? How can I fix this?
问题描述
我建立了一个将紧凑数据字符串解析为JSON的系统.我使用的是19位数字来存储ID.不幸的是,任何大于17位的数字都将parseFloat()
舍入到最后几位数字.
I set up a system that parses a compact data string into JSON. I'm using a 19 digit number to store ids. Unfortunately any number greater than 17 digits, parseFloat()
rounds the last few digits.
这会破坏整个数据字符串.我可以解决这个问题吗?
This breaks the whole data string. Can I fix this?
例如,8246295522085275215
变成了8246295522085276000
.为什么会这样?
For example 8246295522085275215
gets turned into 8246295522085276000
. Why is this?
http://jsfiddle.net/RobertWHurst/mhZ7Q/
推荐答案
JavaScript仅具有一种数字类型,这是IEEE 754双精度浮点数.也就是说,您最多可以有52位精度,这比15位小数位还要多.
JavaScript has only one numeric type, which is an IEEE 754 double precision floating-point. That means, you have a maximum of 52 bits of precision, which is a bit more than 15 decimal places.
如果您需要的精度更高,则必须使用bignum库或使用字符串.
If you need more precision than that, you have to use a bignum library or work with strings.
这篇关于解析浮点数有舍入限制吗?我怎样才能解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!