如何在解析JSON时防止删除小数点? [英] How to prevent removing decimal point when parsing JSON?

查看:516
本文介绍了如何在解析JSON时防止删除小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  var parsed = JSON.parse('{myNum:0.0}' ); 

然后,当您看 parsed.myNum ,你只需得到 0 。 (足够公平。)



如果您执行 parsed.myNum.toString(),您会得到0



基本上,我正在寻找一种方法将它变成字符串 0.0



显然,在现实生活中,我不控制JSON输入,我从Web服务获取JSON ...我想使用浏览器的JSON解析器解析JSON,并且能够识别数字值 0 0.0

有没有办法做到这一点,手动阅读JSON字符串?在这种情况下,这不太可能,我需要使用浏览器的本机JSON解析器来提高速度。 (顺便说一下,Chrome扩展程序;不用担心它在其他浏览器中工作。)

解决方案

没有从 JSON.parse eval 获取位数的方法。即使IBM的十进制提案已被EcmaScript委员会采纳,该数字仍将被解析为IEEE 754浮点数。



看一看 http://code.google.com/p/json -sans-eval / source / browse / trunk / src / json_sans_eval.js ,您可以修改这个简单的JSON解析器以保持精确信息。


If you do this...

var parsed = JSON.parse('{"myNum":0.0}') ;

Then when you look at parsed.myNum, you just get 0. (Fair enough.)

If you do parsed.myNum.toString(), you get "0".

Basically, I'm looking for a way to turn this into the string "0.0".

Obviously, in real life I don't control the JSON input, I get the JSON from a web service... I want to parse the JSON using the browser's JSON parser, and to be able to recognise the difference between the number values 0 and 0.0.

Is there any way to do this, short of manually reading the JSON string? That's not really possible in this case, I need to use the browser's native JSON parser, for speed. (This is for a Chrome extension by the way; no need to worry about it working in other browsers.)

解决方案

There's no way to get the number of digits from JSON.parse or eval. Even if IBM's decimal proposal had been adopted by the EcmaScript committee, the number is still going to be parsed to an IEEE 754 float.

Take a look a http://code.google.com/p/json-sans-eval/source/browse/trunk/src/json_sans_eval.js for a simple JSON parser that you can modify to keep precision info.

这篇关于如何在解析JSON时防止删除小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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