How to keep value as number in JSON.stringify()
16,509
Solution 1
toFixed
returns a string. If you want to output a number, just use parseFloat
:
JSON.stringify({
"payer": "a cat",
"price": parseFloat(amount)
});
I don't think there's a way to output a number to any precision after the decimal without converting it to a string.
Solution 2
I think Number() will work too
The differences are here. I have worked with both in JSON.stringify
var data = JSON.stringify({
"payer": "a cat",
"price": Number(amount)
});
Author by
user4046073
Updated on June 05, 2022Comments
-
user4046073 almost 2 years
I'm trying to use
JSON.stringify()
to parse some values into JSON format. Thatamount
is a string variable.I want the final value in JSON format as a number, but my current way doesn't work. It still comes out as"price":"1.00"
afterJSON.stringify()
. How do I make sure the final value in JSON is a number? Thanks for your help!My current code:
var data = JSON.stringify({ "payer": "a cat", "price": parseFloat(amount).toFixed(2), });
-
RobG over 7 yearsOr just
+amount
. -
juanitogan over 3 yearsmultiply, floor/round/ceil, divide
-
Marco Castanho over 2 yearsWon't this try to convert every string to float, whether the string contains a number or not?
-
Ezequiel Larena over 2 yearsYes. In case you want to avoid that, you should add another validation.