JavaScript千位分隔符/字符串格式 [英] Javascript Thousand Separator / string format

查看:101
本文介绍了JavaScript千位分隔符/字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在寻找一种方法来为字符串或数字的千位分隔符...
(像c#中的String.Format)

解决方案

更新(7年后)



下面原始答案中引用的参考文献是错误的。 是一个内置函数,这正是 kaiser 在下面提出的建议:<$













$ p $ (1234567.89).toLocaleString('en')//用于数字输入
parseFloat(1234567.89)。toLocaleString('en')//用于字符串输入


$ b

下面实现的函数也可以,但是根本没有必要。

< (我想也许我很幸运,并且发现它在2010年是必要的,但是根据这个更可靠的引用,toLocaleString自从ECMAScript第三版[1999]以来一直是标准的一部分,我相信意味着它早在IE 5.5中就已经被支持了。)




Original根据 >这个参考资料没有一个内置的函数来添加逗号给一个数字。但是该页面包含了一个如何自己编写代码的例子:

$ p $ function $ addCommas(nStr){
nStr + = '';
var x = nStr.split('。');
var x1 = x [0];
var x2 = x.length> 1? '。'+ x [1]:'';
var rgx = /(\ d +)(\ d {3})/; (rgx.test(x1)){
x1 = x1.replace(rgx,'$ 1'+','+'$ 2')
;
}
return x1 + x2;




$ b

编辑:
去其他方式(将逗号转换为数字),你可以这样做:

  parseFloat(1,234,567.89.replace /,/ g,''))


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#)

解决方案

Update (7 years later)

The reference cited in the original answer below was wrong. There is a built in function for this, which is exactly what kaiser suggests below: toLocaleString

So you can do:

(1234567.89).toLocaleString('en')              // for numeric input
parseFloat("1234567.89").toLocaleString('en')  // for string input

The function implemented below works, too, but simply isn't necessary.

(I thought perhaps I'd get lucky and find out that it was necessary back in 2010, but no. According to this more reliable reference, toLocaleString has been part of the standard since ECMAScript 3rd Edition [1999], which I believe means it would have been supported as far back as IE 5.5.)


Original Answer

According to this reference there isn't a built in function for adding commas to a number. But that page includes an example of how to code it yourself:

function addCommas(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Edit: To go the other way (convert string with commas to number), you could do something like this:

parseFloat("1,234,567.89".replace(/,/g,''))

这篇关于JavaScript千位分隔符/字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆