Search code examples
javascriptjsonstringparsingnumbers

How to keep value as number in JSON.stringify()


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

});

Solution

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