如何动态地进行十进制格式化

时间:2013-06-27 12:00:29

标签: javascript jquery html

我有一个格式化十进制值的任务。我有一个文本框。用户可以输入不同的值。例如 - 如果它是5位数字1,00,00 如果是这样的6 12,12,33 .. 我该如何动态地做到这一点?

function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var components = yourNumber.toString().split(".");
    //Comma-fies the first part
    components [0] = components [0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

DEMO

2 个答案:

答案 0 :(得分:0)

只需将正则表达式中的3替换为2 ...

$('#number').focusout(function() {
    var a = $('#number').val();
    //Seperates the components of the number
    var components = a.toString().split(".");
    //Comma-fies the first part
    components [0] = components [0].replace(/\B(?=(\d{2})+(?!\d))/g, ","); // here in the regex put 2
});

答案 1 :(得分:0)

此代码几乎与您的代码相同,似乎可以满足您的需求:

function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var components = yourNumber.toString().split(".");
    //Comma-fies the first part
    components[0] = components [0].replace(/\B(?=(\d{2})+(?!\d))/g, ",");
    return components.join('.')
}

$('#number').focusout(function() {
    var a = $('#number').val();
    var newstring = ReplaceNumberWithCommas(a);
    if (a!=newstring)$('#number').val(newstring);
});

变化:

  • 我通过加入两部分来重建字符串
  • 我回来了
  • 我将{3}更改为{2}
  • 我替换了字段的值

Demonstration