Javascript Thousand Separator / string format

2019-01-01 15:42发布

Is there any function in Javascript for formatting number and strings ?

I am looking for a way for thousand separator for string or numbers... (Like String.Format In c#)

12条回答
旧人旧事旧时光
2楼-- · 2019-01-01 15:56
var number = 35002343;

console.log(number.toLocaleString());

for the reference you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

查看更多
谁念西风独自凉
3楼-- · 2019-01-01 16:00

Attempting to handle this with a single regular expression (without callback) my current ability fails me for lack of a negative look-behind in Javascript... never the less here's another concise alternative that works in most general cases - accounting for any decimal point by ignoring matches where the index of the match appears after the index of a period.

const format = num => {
    const n = String(num),
          p = n.indexOf('.')
    return n.replace(
        /\d(?=(?:\d{3})+(?:\.|$))/g,
        (m, i) => p < 0 || i < p ? `${m},` : m
    )
}

[
    format(100),        // "100"
    format(1000),       // "1,000"
    format(1e10),       // "10,000,000,000"  
    format(1000.001001) // "1,000.001001"
]
    .forEach(n => console.log(n))

» Verbose regex explanation (regex101.com)

flow diagram

查看更多
闭嘴吧你
4楼-- · 2019-01-01 16:08

There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number

It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:

$.number(12345.4556, 2);          // -> 12,345.46
$.number(12345.4556, 3, ',', ' ') // -> 12 345,456

You can use it inside input fields directly, which is nicer, using same options like above:

$("input").number(true, 2);

Or you can apply to a whole set of DOM elements using selector:

$('span.number').number(true, 2);
查看更多
妖精总统
5楼-- · 2019-01-01 16:08

I use this:

function numberWithCommas(number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

source: link

查看更多
伤终究还是伤i
6楼-- · 2019-01-01 16:12

I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.

function getFormattedCurrency(num) {
    num = num.toFixed(2)
    var cents = (num - Math.floor(num)).toFixed(2);
    return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}
查看更多
伤终究还是伤i
7楼-- · 2019-01-01 16:14
// thousand separates a digit-only string using commas
// by element:  onkeyup = "ThousandSeparate(this)"
// by ID:       onkeyup = "ThousandSeparate('txt1','lbl1')"
function ThousandSeparate()
{
    if (arguments.length == 1)
    {
        var V = arguments[0].value;
        V = V.replace(/,/g,'');
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        arguments[0].value = V;
    }
    else  if ( arguments.length == 2)
    {
        var V = document.getElementById(arguments[0]).value;
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
}   
查看更多
登录 后发表回答