dsxay48646 2015-09-09 08:16
浏览 117
已采纳

如何用javascript中的千位分隔符计算数字

I've converted numbers using php number format as follows:

number_format($X, 2, ',', '.');

which converts

5000000

into

5.000.000,00

which is exactly what I wanted.

But now my javascript function which is doing some basic math on those numbers are giving wrong result, for example:

5.000.000,00 - 3.500.000,00 = 1.5 instead of 1.500.000,00

So how do you properly calculate those numbers in javascript?

I really appreciate any help i can get :D

Thanks y'all

  • 写回答

1条回答 默认 最新

  • duanmen2189 2015-09-09 08:31
    关注

    Formatted numbers are for human eyes and not suitable for JS processing. You may want to either write the numbers as is in HTML and do the formatting on client side, or add a separate data attribute for the raw value.

    For example:

    <span id="myNumber" data-value="<?=$X?>"><?=number_format($X, 2, ',', '.')?></span>
    

    Which gives you:

    <span id="myNumber" data-value="5000000">5.000.000,00</span>
    

    You can then get the raw number by JS:

    var X = parseInt(document.getElementById("myNumber").getAttribute("data-value"), 10);
    

    Or jQuery:

    var X = parseInt($("#myNumber").attr("data-value"), 10);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?