如何在javascript中将价格转换为有效的价格格式

How to convert a price into a valid price format in javascript?

本文关键字:有效 格格 格式 转换 javascript      更新时间:2023-09-26

我有以下html。

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

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

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

那么anyboby可以解释如何在javascript中完成它吗?

它应该在此字段的按键向下,按键或键向上事件中完成。

谢谢

你可以

试试这个,我在参考中使用了函数

 //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;
}

工作演示

这是来自如何在 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, '.', ','));

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