0

我有以下html。

<input type="text" id="Price">

当用户在此输入字段中输入价格金额时,应自动将其转换为有效的价格格式。

假设用户输入 9200000,它应该自动转换为 9,200,000。

那么任何人都可以解释它是如何在 javascript 中完成的吗?

应该在该字段的 keyDown、keypress 或 keyup 事件中完成。

谢谢

4

3 回答 3

1

你可以试试这个,我在参考中使用过函数

 //Attach event
var el = document.getElementById("Price");
el.onkeydown = function(evt) {
    evt = evt || window.event;
    this.value = addCommas(stripNonNumeric(this.value));
};

// This function removes non-numeric characters
function stripNonNumeric( str )
{
  str += '';
  var rgx = /^\d|\.|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++ )
  {
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

工作演示

于 2013-10-08T09:30:00.777 回答
1

这是来自如何在 JavaScript 中将数字格式化为货币?

Number.prototype.formatMoney = function(c, d, t){
var n = this, 
    c = isNaN(c = Math.abs(c)) ? 2 : c, 
    d = d == undefined ? "." : d, 
    t = t == undefined ? "," : t, 
    s = n < 0 ? "-" : "", 
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", 
    j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };
alert((123456789.12345).formatMoney(2, '.', ','));
于 2013-10-08T09:36:48.407 回答
0

在输入上添加一个事件侦听器并编写一个函数以将逗号插入到您的输入值中,当您收到 keyDown 事件时侦听器调用该值。

于 2013-10-08T09:27:44.567 回答