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.)
where
1
is number of decimal placesEdit:
parsed.myNum
is number,parsed.myNym.toFixed( 1 )
would be stringEdit2: 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 neededIf 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.
There's no way to get the number of digits from
JSON.parse
oreval
. 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.
It shouldn't matter,
00000.00000
is0
if you tryJSON.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 stringJSON.parse('{"myNum":"0.0"}')