Search code examples
javascriptjquerystringcasting

parseFloat() or Number() always return NaN when read from div tag


I have a jquery code in which I am reading a sub-total value from a div tag and then I want to convert it into a javascript number type. So I used the below code.

var cart_subtotal_str = $('.pewc-total-field').text(); // so it strips all HTML tags here
var cart_subtotal = cart_subtotal_str.replace('£', ''); // removes currency sign
var cart_subtotal_num = parseFloat(cart_subtotal); // here it returns NaN

The content of the div is like this

<span id="pewc-grand-total" class="pewc-total-field"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>‎8.40</bdi></span></span>

Any idea why and how do I fix this? I found that if I manually pass some string like this, it works fine.

var cart_subtotal_str = '12.34';

I have already read this answer, this question is not relevant to that Parsefloat always returns NaN


Solution

  • The issue is because you have a non-printable character in your HTML. Most quality IDEs will display these graphically - even the SO snippet editor does this, note the red dot before 8.40

    enter image description here

    Remove that character and your code works fine:

    var cart_subtotal_str = $('.pewc-total-field').text();    
    var cart_subtotal = cart_subtotal_str.replace('£', '');
    var cart_subtotal_num = parseFloat(cart_subtotal);
    
    console.log(cart_subtotal_num);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span id="pewc-grand-total" class="pewc-total-field">
      <span class="woocommerce-Price-amount amount">
        <bdi>
          <span class="woocommerce-Price-currencySymbol">£</span>
          8.40
        </bdi>
      </span>
    </span>

    If, for whatever reason, you don't have access to the HTML, then you can strip any non-numerical value from the HTML before you call parseFloat():

    var cart_subtotal_str = $('.pewc-total-field').text().replace(/[^\d.-]/g, '');
    var cart_subtotal_num = parseFloat(cart_subtotal_str);
    
    console.log(cart_subtotal_num);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span id="pewc-grand-total" class="pewc-total-field">
      <span class="woocommerce-Price-amount amount">
        <bdi>
          <span class="woocommerce-Price-currencySymbol">£</span> 
          ‎8.40
        </bdi>
      </span>
    </span>