javascript parse float error

前端 未结 3 1806
花落未央
花落未央 2021-01-23 02:07

I am trying to get sum of rows of my table:

td1 val = $5,000.00; td2 val = $3000.00;

And I am using the following code:



        
相关标签:
3条回答
  • 2021-01-23 02:20

    Try:

    var totalnum = 0;
    $('.num').each(function(){
       totalnum+= parseFloat($(this).html().substring(1).replace(',',''));
    });
    $('.total_num').html('$' + totalnum);
    

    This will remove the $ (or whatever currency symbol) from the beginning and all commas before doing the parseFloat and put it back for the total.

    Alternatively you could use the jQuery FormatCurrency plugin and do this:

    totalnum+= $(this).asNumber();
    
    0 讨论(0)
  • 2021-01-23 02:27

    If you add $ to the value, it is no longer an integer, and can no longer be calculated with.

    Trying to make the formatted value back into a number is a bad idea. You would have to cater for different currency symbols, different formattings (e.g. 1.000,00) and so on.

    The very best way would be to store the original numeric value in a separate attribute. If using HTML 5, you could use jQuery's data() for it:

    <td class="num" data-value="1.25">$1.25</td>
    ....
    
    var totalnum = 0;
    $('.num').each(function(){
      totalnum+= parseFloat($(this).data("value"));
    });
    $('.total_num').html(totalnum);
    

    this way, you separate the formatted result from the numeric value, which saves a lot of trouble.

    0 讨论(0)
  • 2021-01-23 02:33

    Try removing $ and any other character not part of the float type:

    var totalnum = 0;
    
    $('.num').each(function(){
        var num = ($(this).html()).replace(/[^0-9\.]+/g, "");
        totalnum+= parseFloat(num);
    });
    
    $('.total_num').html(totalnum);
    

    Edit: updated replace to remove all non-numerical characters (except periods) as per this answer.

    0 讨论(0)
提交回复
热议问题