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)
});
Share:
16,509
user4046073
Author by

user4046073

Updated on June 05, 2022

Comments

  • user4046073
    user4046073 almost 2 years

    I'm trying to use JSON.stringify() to parse some values into JSON format. That amount 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" after JSON.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
    RobG over 7 years
    Or just +amount.
  • juanitogan
    juanitogan over 3 years
    multiply, floor/round/ceil, divide
  • Marco Castanho
    Marco Castanho over 2 years
    Won't this try to convert every string to float, whether the string contains a number or not?
  • Ezequiel Larena
    Ezequiel Larena over 2 years
    Yes. In case you want to avoid that, you should add another validation.