Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an html number input always display 2 decimal places

Tags:

html

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?

like image 230
Cristiano Avatar asked Feb 13 '13 20:02

Cristiano


People also ask

How do I put 2 decimal places in HTML?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do I limit the number of decimal places in HTML?

JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

How do you input a decimal value in HTML?

You can also use a decimal value: for example, a step of 0.3 will allow values such as 0.3, 0.6, 0.9 etc, but not 1 or 2. Now you don't get a validation error. Yay! Also note that if you only want to accept positive numbers, you'll want to add min=”0″.

How do you keep a float up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

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.

like image 179
Groot Avatar answered Oct 04 '22 04:10

Groot