I’m confused.
$("#total-kwh-cost").text()
contains the text $920
. It has been previously calculated and formatted using toLocaleString()
as USD currency
and stored in a div
with an id
of #total-kwh-cost
.
I retrieve the text from the div
using:
var tkwhCostp = $("#total-kwh-cost").text().replace(/,/g,''); // returns $920 as text
Then I check it to make sure it’s been a number
console.log("tkwhCostp text is: "+tkwhCostp); // return NaN
console.log("tkwhCostp isNAN? "+isNaN(tkwhCostp)); // returns true
tkwhCostp = parseFloat(tkwhCostp); // Run it through parseFloat
console.log("tkwhCostp text is: "+tkwhCostp); // returns NaN
console.log("tkwhCostp isNAN? "+isNaN(tkwhCostp)); // returns true
I tried parseInt()
and Number()
and get the same results. This has to be local to my code.
It also appears to only affect variables that I converted using toLocaleString()
.
I’m at a loss as to how to convert it back to a number so I can add to the number 920.
2
Answers
Javascript interprets the
$
sign as non-numeric and the entire parsing operation fails, returningNaN
(not a number).To remove the comma and the dollar sign:
It has been previously calculated and formatted using toLocaleString() for better display in HTML which is fine. But why is it then stored in the div to be retrieved later on by JS? You already have the original, unformatted value in JS for your calculations, it’s better to use that instead.
You are getting NaN because tolocaleString() changes the value into a string that cannot be automatically converted to a Number. The parseInt() and Number() functions cannot convert anything into a number. If the first character of a string is not a digit e.g. $, then NaN (Not-a-Number) is returned.