Force two decimal places in input type="number"


I have been asked for something a bit weird, that the fields input numeric of a JSP page have 2 decimals by default.

So far everything is normal:

<input type="number" step="0.01" />

Now, the client wants the quantities to ALWAYS have 2 decimal places, even for 0:

should be:

That is, while you use the arrows to increase the quantity or loads from the database a value with zeros in the decimal places that this value is not trimmed (that is, overwrite the default behavior that ignores the zeros to the right)



I've tried it with pattern="regex" :


but it does not seem to work.


  • As noted rnd : link
  • I've tried a solution via html but if someone comes up with something in javascript / jquery that solves it, it also works for me:).
asked by Jordi Castilla 10.03.2016 в 12:54

2 answers


You can not use the pattern attribute with type="number" , as explained in MDN ( property pattern)


This attribute is applied when the value of type is text, search, tel, url or email; otherwise, it will be ignored.

This focus on JavaScript is very simple and it works. But it is not the most optimal / desirable solution, because for a fraction of a second it shows the 1.1 value before updating to 1.10 , however it can get you out of the block. .

Thanks @AlvaroMontoro! who commented that using input instead of change the latency effect disappears.

var el = document.getElementById("in")

// te aseguras que el valor inicial tiene el formato correcto
el.value = el.valueAsNumber.toFixed(2)

// manejador que asegura que el valor tiene el formato correcto cuando 
// se modifica el valor, ya sea manual o con los botones inc/dec
el.addEventListener('input', function(event) { =
<input id="in" value="1" type="number" step="0.01">
answered by 10.03.2016 в 17:22

I would advise you to use a jquery plugin to apply a mask over the textbox

Masked Input Plugin

Mask Plugin

The idea is that the mask limits the input of the user in the control.


<script src=""></script>
<script src=""></script>

<input type="text" id="textbox1">

Of course this is just an example, you should analyze if you can define a mask that suits what you are looking for. The idea is not to validate but the mask limits what the user enters

answered by 10.03.2016 в 17:35