14

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

});
user4046073
  • 821
  • 4
  • 18
  • 39

5 Answers5

11

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.

Cappielung
  • 322
  • 3
  • 6
4

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)
});
Stavros
  • 743
  • 8
  • 19
0

I had the same problem, creating random float number, this is my solution:

// Create a random float number between 10 and 120, with only 2 decimal place
var number = Math.floor((Math.random()*110+10)*100)/100

So is still a floating value, with 2 decimal place, also after JSON.stringify()

keebOo
  • 83
  • 2
  • 10
0

This way has served me.

function replace(key, value) {
  if (typeof value != "object") {
    let change = parseFloat(value);
    return change;
  }
  return value;
}

const msg = JSON.stringify(params, replace);`

Params is a variable that contains a query parameter.

0
JSON.stringify(obj, (key, value) => {
    if (!isNaN(value))
        value = Number(value)
    return value
})
Fliens
  • 19
  • 1
  • 7