How to prevent removing decimal point when parsing

2020-02-13 22:28发布

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.)

4条回答
Deceive 欺骗
2楼-- · 2020-02-13 22:38
... parsed.myNum.toFixed( 1 ) ...

where 1 is number of decimal places

Edit: parsed.myNum is number, parsed.myNym.toFixed( 1 ) would be string

Edit2: in this case you need to pass value as string {"myNum":'0.0'} and parsed when calculations is needed or detect decimal separator, parsed number, and use decimal separator position when string is needed

查看更多
乱世女痞
3楼-- · 2020-02-13 22:39

If 0.0 is not enclosed in quotes in your JSON (i.e. it's a number and not a string), then there's no way to distinguish it from 0, unless you write your own JSON parser.

查看更多
不美不萌又怎样
4楼-- · 2020-02-13 22:41

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.

查看更多
一夜七次
5楼-- · 2020-02-13 22:43

It shouldn't matter, 00000.00000 is 0 if you try JSON.parse('{"myNum":0.00001}') you'll see a value of { myNum=0.0001 } If you really need it to hold the decimal you'll need to keep it a string JSON.parse('{"myNum":"0.0"}')

查看更多
登录 后发表回答