html 金额字段输入,如何将输入的文本格式化为HTML文本字段,如货币?

这里有一段代码,我很久以前用逗号来编写一个数字。一个例子是formatNumber(349507, 0, 2, true)→ "349,507.00"。

// Reformats a number by inserting commas and padding out the number of digits

// and decimal places.

//

// Parameters:

// number: The number to format. All non-numeric characters are

// stripped out first.

// digits: The minimum number of digits to the left of the decimal

// point. The extra places are padded with zeros.

// decimalPlaces: The number of places after the decimal point, or zero to

// omit the decimal point.

// withCommas: True to insert commas every 3 places, false to omit them.

function formatNumber(number, digits, decimalPlaces, withCommas)

{

number = number.toString();

var simpleNumber = '';

// Strips out the dollar sign and commas.

for (var i = 0; i < number.length; ++i)

{

if ("0123456789.".indexOf(number.charAt(i)) >= 0)

simpleNumber += number.charAt(i);

}

number = parseFloat(simpleNumber);

if (isNaN(number)) number = 0;

if (withCommas == null) withCommas = false;

if (digits == 0) digits = 1;

var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number));

var string = "";

for (var i = 0; i < digits || integerPart > 0; ++i)

{

// Insert a comma every three digits.

if (withCommas && string.match(/^\d\d\d/))

string = "," + string;

string = (integerPart % 10) + string;

integerPart = Math.floor(integerPart/10);

}

if (decimalPlaces > 0)

{

number -= Math.floor(number);

number *= Math.pow(10, decimalPlaces);

string += "." + formatNumber(number, decimalPlaces, 0);

}

return string;

}您可以在onblur事件处理程序上使用它,如下所示:

这会给数字加上逗号,并在前面贴一个美元符号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值