Javascript jQuery函数用逗号和小数格式化数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14075014/
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
jQuery function to to format number with commas and decimal
提问by Jeff
I'm using the following function to format numbers as the user types. It will insert a comma every 3 numbers. Ex: 45696.36becomes 45,696.36.
我正在使用以下函数将数字格式化为用户类型。它将每 3 个数字插入一个逗号。例如:45696.36变成45,696.36。
However, I've run into a problem with it. If the numbers after the decimal are longer than 3 digits, it starts adding commas to them. Ex: 1136.6696becomes 1,136.6,696.
但是,我遇到了问题。如果小数点后的数字超过 3 位,则开始向它们添加逗号。例如:1136.6696变成1,136.6,696。
This is my function:
这是我的功能:
$.fn.digits = function(){
return this.each(function() {
$(this).val( $(this).val().replace(/[^0-9.-]/g, '') );
$(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",") );
})
}
How can I fix this so it stops placing commas after the decimal? I'm using jQuery 1.8. Thanks!
我该如何解决这个问题,让它停止在小数点后放置逗号?我正在使用 jQuery 1.8。谢谢!
回答by Rion Williams
You could accomplish this by splitting your string at the '.' character and then performing your comma-conversion on the first section only, as such:
您可以通过在 ' .' 字符处拆分字符串,然后仅在第一部分执行逗号转换来完成此操作,如下所示:
function ReplaceNumberWithCommas(yourNumber) {
//Seperates the components of the number
var n= yourNumber.toString().split(".");
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return n.join(".");
}
ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696

