Alternative to JSON.parse () to maintain decimal precision?

I am calling JSON.parse()to parse JSON strings with small decimal places.

Decimal precision is not supported after parsing. For example, instead of the actual decimal value, a type value is returned 3.1e-7.

How can I deserialize a JSON string to ng2 + while maintaining decimal precision?

UPDATE

I thought about displaying values ​​from a string and then manually setting the values ​​for the object after JSON.parse (), but when I set another small decimal number as the property value, the same number is formatted. Is this problem not necessarily unique to JSON.parse (), but to Javascript in general? Or is JSON.parse () somehow setting property types in a fixed way?

+4
source share
1 answer

Once you pass the JSON string through JSON.parse, you will lose precision due to the way the floating point math works . You will need to save this number as an object intended for storing arbitrary precision numbers , and before parsing it, you will need to bother with the string itself. The easiest way is with regular expressions. JSON is context free grammar, and regular expressions work with regular grammars, so a warning applies:

WARNING: PARSING CFG WITH REGEX CAN SUMMON LOAD

This regular expression should turn the numbers in your JSON into strings:

let stringedJSON = origJSON.replace(/:\s*([-+Ee0-9.]+)/g, ': "uniqueprefix$1"');

, , , data:42.

, , stringedJSON - {"foo": "uniqueprefix0.00000017", "bar": "an actual string"}. JSON.parse , uniqueprefix0.00000017 - , . JSON.parse reviver, . , :

let o = JSON.parse(stringedJSON, (key, value) => {
  // only changing strings
  if (typeof value !== 'string') return value;
  // only changing number strings
  if (!value.startsWith('uniqueprefix')) return value;
  // chop off the prefix
  value = value.slice('uniqueprefix'.length);
  // pick your favorite arbitrary-precision library
  return new Big(value);
});
+3

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


All Articles