Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON stringify conversion of float to int

I am using Node.js and the built-in JSON object to stringify a JSON object. In the object is

{ 
    weight : 1.0
}

However when I stringify and write to a file the output is weight : 1.

like image 508
kyleED Avatar asked May 21 '13 04:05

kyleED


People also ask

Does JSON Stringify work on numbers?

JSON.stringify() converts a value to JSON notation representing it: Boolean , Number , String , and BigInt (obtainable via Object() ) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics.

What does JSON Stringify () method do?

The JSON.stringify() function will convert any dates into strings.

Does JSON Stringify convert date to UTC?

stringify converts DateTimeOffset to UTC format #1710.

What is reverse of JSON Stringify?

JSON. parse is the opposite of JSON. stringify .


2 Answers

As noted in this answer to a similar question, and on this MSDN page:

There is no such thing as an integer in JavaScript. Numbers in JavaScript are "double-precision 64-bit format IEEE 754 values".

Open up your web browser's console and type 1.0. You'll see 1 printed out. All numbers in JavaScript are floating point numbers, so your serializer simply chose to leave off unnecessary precision.

like image 78
Trey Hunner Avatar answered Oct 16 '22 13:10

Trey Hunner


Actually yours is not an issue , 1 == 1.0 == 1.00 in Javascript and if you have a float value like 1.55 then stringify gives you the same 1.55 not 1.. Even then if you want 1.0 to be written , change the value into string

I mean Enclose the value in double quotes

{ 
    weight : "1.0"
}
like image 37
Prasath K Avatar answered Oct 16 '22 13:10

Prasath K