skip to Main Content

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


  1. Javascript interprets the $ sign as non-numeric and the entire parsing operation fails, returning NaN (not a number).

    To remove the comma and the dollar sign:

    var tkwhCostp = $("#total-kwh-cost").text().replace(/,/g,'').replace(/$/g, ''); // returns 920 as text
    
    Login or Signup to reply.
  2. 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.

    let originalValue = 920;
    let formatedValue = originalValue.toLocaleString("en-US", {style:"currency", currency:"USD"});
    $("#total-kwh-cost").text(formatedValue); // use the formatted value in HTML for display
    let calculatedValue = originalvalue * 0.25; // use the original value for math calculations
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search