HTML 5货币格式 [英] HTML 5 Currency format
问题描述
我在我的网页中使用了大量HTML 5输入控件。我的要求之一是有一个带有货币功能的文本框。为此我尝试了这个:
< input type =numberpattern =(d {3})([。 ])(d {2})/>
这允许我输入类似10,000.00的值
<但它仍然不符合我的所有要求。我想,如果用户输入10000
,它应该将其转换为10,000像onblur这样的货币格式。
当我从输入类型中读取值我的Javascript,它应该给我一个浮点数,而不是一个字符串值,我不能用它来计算而不解析。
解决方法是使用额外的 input type =text
:
HTML
< input type =textid =userinputpattern =[0-9] *>
< br>
< input type =numberid =number>
JS
document.getElementById(userinput)。onblur = function(){
//数字格式用户输入
this.value = parseFloat(this.value.replace (/,/ g,))
.toFixed(2)
.toString()
.replace(/ \B(?=(\ d {3})+ (?!\d))/ g,,);
//将数字值设置为数字输入
document.getElementById(number)。value = this.value.replace(/,/ g,)
}
正则表达式来自这里如何在JavaScript中使用逗号作为千位分隔符来打印数字
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:
<input type="number" pattern="(d{3})([.])(d{2})" />
This allows me to type values like 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.
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.
Here's a workaround with an additional input type="text"
:
HTML
<input type="text" id="userinput" pattern="[0-9]*">
<br>
<input type="number" id="number">
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
这篇关于HTML 5货币格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!