HTML 5 货币格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18308862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML 5 Currency format
提问by user2561997
I am using lots of HTML 5 input controls in my pages. One of my requirement is to have a textbox with currency feature. For this i tried this:
我在我的页面中使用了很多 HTML 5 输入控件。我的要求之一是有一个带有货币功能的文本框。为此,我试过这个:
<input type="number" pattern="(d{3})([.])(d{2})" />
This allows me to type values like 10,000.00
这允许我输入像 10,000.00 这样的值
But still all its not meeting all my requirements. I want that if the user types in 10000 it should convert it to currency format like 10,000 onblur.
但仍然没有满足我的所有要求。我希望如果用户输入 10000,它应该将其转换为货币格式,如 10,000 onblur。
And when i read the value from the input type in my Javascript, it should give me a float instead of a string value which i cannot use to calculate without parsing.
当我从我的 Javascript 中的输入类型读取值时,它应该给我一个浮点数而不是一个字符串值,我不能在不解析的情况下使用它来计算。
回答by Max Girkens
Here's a workaround with an additional input type="text"
:
这是一个额外的解决方法input type="text"
:
HTML
HTML
<input type="text" id="userinput" pattern="[0-9]*">
<br>
<input type="number" id="number">
JS
JS
document.getElementById("userinput").onblur =function (){
//number-format the user input
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//set the numeric value to a number input
document.getElementById("number").value = this.value.replace(/,/g, "")
}
regex is from here How to print a number with commas as thousands separators in JavaScript
正则表达式来自这里如何在 JavaScript 中使用逗号作为千位分隔符打印数字
回答by Amith
try this - http://jsbin.com/azOSayA/1/edit
试试这个 - http://jsbin.com/azOsayA/1/edit
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, ''+','+'');
}
return val;
}
$('#elementID').focusout(function(){
alert(commaSeparateNumber($(this).val()));
});