jQuery函数以逗号和十进制格式格式化数字 [英] jQuery function to to format number with commas and decimal

查看:261
本文介绍了jQuery函数以逗号和十进制格式格式化数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下功能来根据用户类型设置数字格式.它将每3个数字插入一个逗号.例如:45696.36变为45,696.36.

I'm using the following function to format numbers as the user types. It will insert a comma every 3 numbers. Ex: 45696.36 becomes 45,696.36.

但是,我遇到了问题.如果小数点后的数字大于3位,则会开始在其中添加逗号.例如:1136.6696变为1,136.6,696.

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.6696 becomes 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.谢谢!

How can I fix this so it stops placing commas after the decimal? I'm using jQuery 1.8. Thanks!

推荐答案

您可以通过在'.'字符处分割字符串,然后仅在第一部分执行逗号转换来实现此目的,例如:

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

示例

Example

这篇关于jQuery函数以逗号和十进制格式格式化数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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