使一个html数字输入始终显示2个小数位 [英] Make an html number input always display 2 decimal places

查看:418
本文介绍了使一个html数字输入始终显示2个小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个表单,用户可以使用html数字输入标记输入美元金额。有没有办法让输入框始终显示2个小数位? 所以如果有人在这里绊倒这里是一个解决此问题的JavaScript解决方案:



第1步:将HTML数字输入框挂钩到 onchange event

  myHTMLNumberInput.onchange = setTwoNumberDecimal; 

或者在html代码中,如果您喜欢的话

 < input type =numberonchange =setTwoNumberDecimalmin =0max =10step =0.25value =0.00/> 

第2步:编写setTwoDecimalPlace方法

 函数setTwoNumberDecimal(event){
this.value = parseFloat(this.value).toFixed(2);

$ / code>

通过将中的'2'更改为Fixed 如果您愿意,您可以获得更多或更少的小数位。


I'm making a form where the user can enter a dollar amount using an html number input tag. Is there a way to have the input box always display 2 decimal places?

解决方案

So if someone else stumbles upon this here is a JavaScript solution to this problem:

Step 1: Hook your HTML number input box to an onchange event

myHTMLNumberInput.onchange = setTwoNumberDecimal;

or in the html code if you so prefer

<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />

Step 2: Write the setTwoDecimalPlace method

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(2);
}

By changing the '2' in toFixed you can get more or less decimal places if you so prefer.

这篇关于使一个html数字输入始终显示2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆