如何动态设置十进制格式

How to do decimal formatting dynamically

本文关键字:设置 十进制 格式 动态 何动态      更新时间:2023-09-26

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

演示

只需将正则表达式中的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
});

这段代码几乎和你的代码一样,似乎可以做你想做的事:

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}
  • 我替换字段的值

演示