How to prevent removing decimal point when parsing JSON?

后端 未结 4 1403
灰色年华
灰色年华 2020-12-11 16:36

If you do this...

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

Then when you look at parsed.myNum, you just get 0

相关标签:
4条回答
  • 2020-12-11 17:12

    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.

    0 讨论(0)
  • 2020-12-11 17:13

    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"}')

    0 讨论(0)
  • 2020-12-11 17:15
    ... 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

    0 讨论(0)
  • 2020-12-11 17:29

    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.

    0 讨论(0)
提交回复
热议问题