How to prevent decimal point removal while parsing 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 do not control JSON input, I get JSON from a web service ... I want to parse JSON using a browser JSON analyzer and be able to recognize the difference between the numerical values 0 and 0.0 .

Is there a way to do this, apart from manually reading a JSON string? In this case, this is not real, I need to use my own JSON analyzer for speed. (By the way, for the Chrome extension, you don’t have to worry about it while working in other browsers.)

+4
source share
4 answers

There is no way to get the number of digits from JSON.parse or eval . Even if IBM accepted the decimal proposal adopted by the EcmaScript committee, the number will still be parsed by the IEEE 754 floating point.

Check out 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 save accuracy information.

+4
source

If 0.0 is not quoted in your JSON (i.e., this is a number, not a string), then there is no way to distinguish it from 0 unless you wrote your own JSON parser.

+6
source
 ... parsed.myNum.toFixed( 1 ) ... 

where 1 is the number of decimal places

Edit: parsed.myNum - number, parsed.myNym.toFixed( 1 ) will be a string

Edit2: in this case, you need to pass the value as a string {"myNum":'0.0'} and parse when you need calculations or determine the decimal separator, the parse number and use the decimal separator when a string is required

+1
source

It does not matter, 00000.00000 is 0 , if you try JSON.parse('{"myNum":0.00001}') , you will see the value { myNum=0.0001 } . If you really need to hold the decimal number, you will need to save the string JSON.parse('{"myNum":"0.0"}')

0
source

Source: https://habr.com/ru/post/1346331/


All Articles