javascript - Best way to deal with very large Long numbers in Ajax? - Stack Overflow

Javascript represents all numbers as double-precision floating-point.This means it loses precision wh

Javascript represents all numbers as double-precision floating-point. This means it loses precision when dealing with numbers at the very highest end of the 64 bit Java Long datatype -- anything after 17 digits. For example, the number:

714341252076979033

... bees:

714341252076979100

My database uses long IDs and some happen to be in the danger zone. I could change the offending values in the database, but that'd be difficult in my application. Instead, right now I rather laboriously ensure the server encodes Long IDs as Strings in all ajax responses.

However, I'd prefer to deal with this in the Javascript. My question: is there a best practice for coercing JSON parsing to treat a number as a string?

Javascript represents all numbers as double-precision floating-point. This means it loses precision when dealing with numbers at the very highest end of the 64 bit Java Long datatype -- anything after 17 digits. For example, the number:

714341252076979033

... bees:

714341252076979100

My database uses long IDs and some happen to be in the danger zone. I could change the offending values in the database, but that'd be difficult in my application. Instead, right now I rather laboriously ensure the server encodes Long IDs as Strings in all ajax responses.

However, I'd prefer to deal with this in the Javascript. My question: is there a best practice for coercing JSON parsing to treat a number as a string?

Share Improve this question asked Apr 2, 2011 at 20:50 Dean MosesDean Moses 2,3822 gold badges24 silver badges36 bronze badges 1
  • You'd have to write your own parser, probably. I doubt any stock JSON parser would have an option to do such a thing. – Pointy Commented Apr 2, 2011 at 20:54
Add a ment  | 

2 Answers 2

Reset to default 9

You do have to send your values as strings (i.e. enclosed in quotes) to ensure that Javascript will treat them as strings instead of numbers.

There's no way I know of to get around that.

JavaScript represents all numbers as 64b IEEE 754 floats.

If your integer can't fit in 52 bits then it will be truncated which is what happened here.

If you do need to change your database, change it to send 52 bit integers. Or 53 bit signed integers.

Otherwise, send them as strings.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744363869a4570603.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信