Maintain decimal points with 0 in JSON object [duplicate] - javascript

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.)

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.

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.

... 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

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

Related

alternative to JSON.parse() for maintaining decimal precision?

I'm calling JSON.parse() to parse a JSON string which has small decimals.
The precision of the decimals is not being maintained after parsing. For example, a value like 3.1e-7 is being returned instead of the actual decimal.
How can I deserialize a JSON string in ng2+ while maintaining decimal precision?
UPDATE
I was thinking about mapping out the values from the string and then setting the values manually to the object after JSON.parse() but when I set a different small decimal number as a property value, the same number formatting occurs. So is this problem not necessarily unique to JSON.parse() but to Javascript in general? Or does JSON.parse() somehow configure property types in a fixed way?
As soon as you pass your JSON string through JSON.parse, you'll lose precision because of the way floating point math works. You'll need to store the number as an object designed for storing arbitrary-precision numbers, and you'll need to fiddle with the string itself before parsing it. The simplest way is with regexes. JSON is a context free grammar, and regexes work on regular grammars, so the warning applies:
WARNING: PARSING CFG WITH REGEX MAY SUMMON ZALGO
This regex should turn the numbers in your JSON into strings:
let stringedJSON = origJSON.replace(/:\s*([-+Ee0-9.]+)/g, ': "uniqueprefix$1"');
But I haven't tested it extensively and it definitely will screw things up if you have keys that are something like data:42.
Assuming it worked correctly, stringedJSON should now be something like {"foo": "uniqueprefix0.00000017", "bar": "an actual string"}. You can parse this with JSON.parse without losing precision, but uniqueprefix0.00000017 isn't what you want. JSON.parse can be called with an extra reviver argument, which transforms values passed to it before returning them. You can use this to convert your data back into a useful form:
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);
});

Angular / Javascript 'rounding' long values?

I have the following JSON:
[{"hashcode": 4830991188237466859},{...}]
I have the following Angular/JS code:
var res = $resource('<something>');
...
res.query({}, function(json) {hashcode = json[0].hashcode;};
...
Surprisingly (to me, I'm no JS expert), I find that something (?) is rounding the value to the precision of 1000 (rounding the last 3 digits). This is a problem, since this is a hash code of something.
If, on the other hand I write the value as a String to the JSON, e.g -
[{"hashcode": "4830991188237466859"},{...}]
this does not happen. But this causes a different problem for me (with JMeter/JSON Path, which extracts the value ["4830991188237466859"] by running my query $.hashcode - which I can't use as a HTTP request parameter (I need to add ?hashcode=... to the query, but I end up with ?hashcode=["..."]
So I appreciate help with:
Understanding who and why -- is rounding my hash, and how to avoid it
Help with JMeter/JSON Path
Thanks!
Each system architecture has a maximum number it can represent. See Number.MAX_VALUE or paste your number into the console. You'll see it happens at the JavaScript level, nothing to do with angular. Since the hash doesn't represent the amount of something, it's perfectly natural for it to be a string. Which leads me to
Nothing wrong with site.com/page?hashcode=4830991188237466859 - it's treated as a string there and you should keep treating it as such.
The javascript Number type is floating point based, and can only represent all integers in the range between -253 and 253. Some integers outside this range are therefore subject to "rounding" as you experience.
In regards to JMeter JSON Path Extractor plugin, the correct JSON Path query for your hashcode will look like
$..hashcode[0]
See Parsing JSON chapter of the guide for XPath to JSON Path mappings and more details.

How to round off 9999999999999999 to 9999999999999998

In my case, i am converting a string value of '9999999999999999' to integer using parseFloat(). But it converts to next number of it i.e. 10000000000000000. But i need to convert it to before of that number i.e. 999999999999999998. I have searched for a while in google. But could not get clear idea to implement this.
Try this
document.getElementById("demo").innerHTML=Math.round(9999999999999999-2);
OUTPUT
9999999999999998
This number is too big to represented precisely in JavaScript Number value. So no amount of conversion will give you values reliably/precisly as you want around such range.
I.e. (9999999999999999-1)===(9999999999999999) returns true, but (9999999999999998)===(9999999999999999) returns false.
If you need such high precision in JavaScript (similar to many other languages) you need to use specialized data types (unfortunately there is no "BigInteger" type built in in JavaScript).
You will need to use some external javascript library to work with big numbers like that, cause max number you cant represent without losing presicion in javascript integers is 9007199254740992 (Explanation : What is JavaScript's highest integer value that a Number can go to without losing precision?)
Here you have some link where people discuss about some libraries to use for javascript big numbers.
How to deal with big numbers in javascript

Parse json in javascript - long numbers get rounded

I need to parse a json that contains a long number (that was produces in a java servlet). The problem is the long number gets rounded.
When this code is executed:
var s = '{"x":6855337641038665531}';
var obj = JSON.parse(s);
alert (obj.x);
the output is:
6855337641038666000
see an example here: http://jsfiddle.net/huqUh/
why is that, and how can I solve it?
As others have stated, this is because the number is too big. However, you can work around this limitation by sending the number as a string like so:
var s = '{"x":"6855337641038665531"}';
Then instead of using JSON.parse(), you can use a library such as javascript-bignum to work with the number.
It's too big of a number. JavaScript uses double-precision floats for numbers, and they have about 15 digits of precision (in base 10). The highest integer that JavaScript can reliably save is something like 251.
The solution is to use reasonable numbers. There is no real way to handle such large numbers.
The largest number JavaScript can handle without loss of precision is 9007199254740992.
I faced this issue some time ago, I was able to solve using this lib: https://github.com/josdejong/lossless-json
You can check this example:
let text = '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}';
// JSON.parse will lose some digits and a whole number:
console.log(JSON.stringify(JSON.parse(text)));
// '{"normal":2.3,"long":123456789012345680000,"big":null}' WHOOPS!!!
// LosslessJSON.parse will preserve big numbers:
console.log(LosslessJSON.stringify(LosslessJSON.parse(text)));
// '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}'

How to prevent removing decimal point when 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 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.)
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.
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.
... 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
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"}')

Categories

Resources