问题描述
我只想问一下如何制作输入类型文本的货币格式的JavaScript.输入数字时数字是否可能带有逗号?另外,如何使数字固定为2个十进制数字.如果我输入一个3位小数,最后一个数字将四舍五入,因此可以是2位小数.
I just want to ask how to make a JavaScript of currency format of input type text. Is it possible that the numbers will have comma while you type the number? Also, how to make the number fixed with 2 decimal numbers. If I input a 3 decimal placed numbers the last number will round off so it can be 2 decimal.
我有一个仅接受数字的文本框,我希望它自动将数字转换为货币格式. 1234.556
将为Php 1,234.56
. (Php的意思是菲律宾比索)
I have a textbox which accepts numbers only and I want it to automatically convert the numbers into currency format. 1234.556
will be Php 1,234.56
. (Php means Philippine peso)
这是我的输入类型文字:
Here's my input type text:
<input type="text" name='Etxt11' placeholder="Proposed price" onblur="this.value = 'Php ' + formatNumber(this.value)" />
推荐答案
function formatPera(num) {
var p = num.toFixed(2).split(".");
return "Php " + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
var money = 1234.556;
money = formatPera(money);
console.log(money); // Php 1,234.56
此外,功劳归功于: https://stackoverflow.com/a/5342097/1978142
这篇关于输入类型的货币格式,逗号和小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!