Javascript Javascript千位分隔符/字符串格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3753483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Thousand Separator / string format
提问by LostLord
Is there any function in Javascript for formatting number and strings ?
Javascript 中是否有用于格式化数字和字符串的函数?
I am looking for a way for thousand separator for string or numbers... (Like String.Format In c#)
我正在寻找一种用于字符串或数字的千位分隔符的方法......(如 c# 中的 String.Format)
回答by Tim Goodman
Update (7 years later)
更新(7年后)
The reference cited in the original answer below was wrong. There isa built in function for this, which is exactly what kaisersuggests below: toLocaleString
下面原始答案中引用的参考是错误的。这里是一个内置的功能,这一点,而这正是德皇以下建议: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 wasnecessary 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.)
(我想也许我会很幸运并在 2010 年发现它是必要的,但没有。根据这个更可靠的参考,toLocaleString 自 ECMAScript 3rd Edition [1999] 以来一直是标准的一部分,我相信这意味着它早在 IE 5.5 就支持了。)
Original Answer
原答案
According to this referencethere 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, '' + ',' + '');
}
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,''))
回答by kaiser
If is about localizingthousands separators, delimiters and decimal separators, go with the following:
如果是关于本地化千位分隔符、分隔符和小数点分隔符,请使用以下内容:
// --> numObj.toLocaleString( [locales [, options] ] )
parseInt( number ).toLocaleString();
There are several options you can use (and even locales with fallbacks):
您可以使用多种选项(甚至带有回退的语言环境):
number = 123456.7089;
result = parseInt( number ).toLocaleString() + "<br>";
result += number.toLocaleString( 'de-DE' ) + "<br>";
result += number.toLocaleString( 'ar-EG' ) + "<br>";
result += number.toLocaleString( 'ja-JP', {
style : 'currency',
currency : 'JPY',
currencyDisplay : 'symbol',
useGrouping : true
} ) + "<br>";
result += number.toLocaleString( [ 'jav', 'en' ], {
localeMatcher : 'lookup',
style : 'decimal',
minimumIntegerDigits : 2,
minimumFractionDigits : 2,
maximumFractionDigits : 3,
minimumSignificantDigits : 2,
maximumSignificantDigits : 3
} ) + "<br>";
var el = document.getElementById( 'result' );
el.innerHTML = result;
<div id="result"></div>
Details on the MDN info page.
Edit:Commentor @I like Serenaadds the following:
编辑:评注@I像Serena添加以下:
To support browsers with a non-English locale where we still want English formatting, use
value.toLocaleString('en')
. Also works for floating point.
要支持我们仍需要英语格式的非英语语言环境的浏览器,请使用
value.toLocaleString('en')
. 也适用于浮点。
回答by Emissary
Updated using look-behind support in line with ECMAScript2018 changes.
For backwards compatibility, scroll further down to see the original solution.
使用后视支持根据 ECMAScript2018 更改进行了更新。
为了向后兼容,请进一步向下滚动以查看原始解决方案。
A regular expression may be used - notably useful in dealing with big numbers stored as strings.
可以使用正则表达式 - 在处理存储为字符串的大数字时特别有用。
const format = num =>
String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, ',')
;[
format(100), // "100"
format(1000), // "1,000"
format(1e10), // "10,000,000,000"
format(1000.001001), // "1,000.001001"
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001
]
.forEach(n => console.log(n))
» Verbose regex explanation (regex101.com)
This original answer may not be required but can be used for backwards compatibility.
这个原始答案可能不是必需的,但可用于向后兼容。
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.
尝试使用单个正则表达式(没有回调)处理这个问题,我目前的能力使我失败,因为在 Javascript 中缺乏负面的后视……这里是另一个适用于大多数一般情况的简洁替代方案 - 考虑任何小数点通过忽略匹配项索引出现在句点索引之后的匹配项。
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"
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001
]
.forEach(n => console.log(n))
回答by qdev
There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number
有一个不错的 jQuery 数字插件: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:
或者您可以使用选择器应用于一整套 DOM 元素:
$('span.number').number(true, 2);
回答by Abhishek Goel
回答by h.foroutan
// 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, ',');
}
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, ',');
}
document.getElementById(arguments[1]).innerHTML = V;
}
else return false;
}
回答by vikashraj144
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
对于参考,您可以在此处查看 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
回答by Awtszs
You can use javascript. below are the code, it will only accept
numeric and one dot
您可以使用 JavaScript。下面是代码,它只会accept
数字和一个dot
here is the javascript
这是javascript
<script >
function FormatCurrency(ctrl) {
//Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
return;
}
var val = ctrl.value;
val = val.replace(/,/g, "")
ctrl.value = "";
val += '';
x = val.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '' + ',' + '');
}
ctrl.value = x1 + x2;
}
function CheckNumeric() {
return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
}
</script>
HTML
HTML
<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />
回答by Ricardo
number = 123456.7089;
result = parseInt( number ).toLocaleString() + "<br>";
result = number.toLocaleString( 'pt-BR' ) + "<br>";
var el = document.getElementById( 'result' );
el.innerHTML = result;
<div id="result"></div>