George M. George M. - 4 months ago 7
JSON Question

Pushing float to object transforms it into a string

I am using the following code:

entries.category[newcat].subcategory[newsub].items[n] = {
name: $("#name").val(),
shortcut: $("#short").val(),
description: $("#desc").val(),
price: parseFloat($("#price").val()).toFixed(2),
vat: parseFloat($("#vat").val()).toFixed(2)
};


Yet, when I immediately check using
JSON.stringify
, both
price
and
VAT
are appended as strings i.e. "10.50" (rather than 10.50).

QUESTION: how do I make sure that price and VAT are stored as float?

Many thanks!

Answer

Using toFix(2) coverts the result back to string. To maintain the value as float, you need to pass the result of toFix(2) into another parseFloat

parseFloat(parseFloat($("#vat").val()).toFixed(2))