-1

我有一个格式化十进制值的任务。我有一个文本框。用户可以输入不同的值。例如 - 如果它是 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, ",");
}

演示

4

2 回答 2

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
});
于 2013-06-27T12:04:09.730 回答
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}
  • 我替换了字段的值

示范

于 2013-06-27T12:04:51.403 回答