4 ms·
I will be the contrarian: JSON numbers are not floating point values, they are strings of characters matching the format "-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?
by tadfisher 3y ago
I will be the contrarian: JSON numbers are not floating point values, they are strings of characters matching the format "-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?". You can choose to parse them however you want, and parsing libraries should provide a mechanism to decode to an arbitrary-precision value.
- koreth1 3y agoBy way of example: when I worked on payment code in Java, we accepted numeric JSON values in request payloads but they were deserialized into "BigDecimal" fields in our payload classes, not "float" or "double".
- lolpanda 3y agoGood point. it's not a problem with JSON. It's just that most of the JSON libraries by default parse numbers into floats.
- int_19h 3y agoRegardless of what the libraries should be doing, there is the reality of what they are doing.
- tadfisher 3y agoLuckily, there are not many broken JSON parsers out there, as this is a well-known issue. Just about the only parser that remains broken is Javascript's JSON.parse(), because it doesn't allow for any options to control the parser, which is why we keep having this discussion.
- meekaaku 3y agoYes, but say in javascript if you do a JSON.parse(), it will give you a double float right?
- tadfisher 3y agoYes, because JSON.parse() treats the input as if it were a JS object literal; that is, JSON.parse(JSON.stringify(someObject)) will be idempotent. Usually parser libraries let you construct a parser with options, so you'd make a "let json = JSON({parseNumbersAsBignums: true})" and use that everywhere, but JS doesn't have that built in.