gpt4 book ai didi

javascript - jQuery 函数用逗号和小数格式化数字

转载 作者:可可西里 更新时间:2023-11-01 01:55:18 28 4
gpt4 key购买 nike

我正在使用以下函数在用户键入时格式化数字。它将每 3 个数字插入一个逗号。例如:45696.36 变为 45,696.36

但是,我遇到了一个问题。如果小数点后的数字超过 3 位,它开始向它们添加逗号。例如:1136.6696 变为 1,136.6,696

这是我的功能:

$.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, "$1,") );
})
}

如何解决此问题,使其停止在小数点后放置逗号?我正在使用 jQuery 1.8。谢谢!

最佳答案

您可以通过在 '.' 字符处拆分您的字符串,然后仅对第一部分执行逗号转换来完成此操作,如下所示:

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

Example

关于javascript - jQuery 函数用逗号和小数格式化数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075014/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com