如何在javascript中将价格转换为有效的价格格式
How to convert a price into a valid price format in javascript?
我有以下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 事件时调用该值。
相关文章:
- 如何有效地将游戏数据存储在URL查询字符串中
- 如何使用Node.js最有效地解析网页
- jquery代码在Mozilla中有效,但在其他浏览器上无效
- 有效形式-始终只显示1个错误[角度]
- Javascript袖珍参考,第121页:这是怎么回事;猴子补丁”;方法应该有效
- 单击仅在第二次单击后有效
- 什么'是在asp.net MVC中将本地化的resources.resx文件转换为javascript文件的有效
- 为什么自我执行匿名有效
- D3.js生成有效的SVG,但不显示任何内容
- 如何在AngularJS中有效地检查日期是否有效
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 滚动在Chrome中有效,但在Firefox或IE中无效
- 有效地获取两个区间之间的随机整数
- Rails将JavaScript对象存储到Model的有效方式
- Javascript XMLHttpRequest——只有第一个POST请求有效
- 使用条件语句,使 jquery fadeIn/fadeOut 仅在视口 >= 480px 时才有效
- 有效负载字节与实际字节不同
- 如何在three.js中有效地使用TraingleStripDrawMode
- 外部链接的Javascript文件赢得't执行,但函数有效
- 如何有效地创建多维javascript数组