Format numbers in JavaScript similar to C#

后端 未结 18 2295
傲寒
傲寒 2020-11-22 12:26

Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString(\"format_provider\") or

18条回答
  •  一生所求
    2020-11-22 12:56

    I wrote a simple function (not yet another jQuery plugin needed!!) that converts a number to a decimal separated string or an empty string if the number wasn't a number to begin with:

    function format(x) {
        return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    

    format(578999); results in 578,999

    format(10); results in 10

    if you want to have a decimal point instead of a comma simply replace the comma in the code with a decimal point.

    One of the comments correctly stated this only works for integers, with a few small adaptions you can make it work for floating points as well:

    function format(x) {
        if(isNaN(x))return "";
    
        n= x.toString().split('.');
        return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
    }
    

提交回复
热议问题