How can I make the HTML5 number field display trailing zeroes?

Akshat picture Akshat · Oct 17, 2011 · Viewed 15.5k times · Source

I have a field:

<input type='number' />

I'd like to punch in 0.50 without it “correcting it” to 0.5, so it would display 0.50.

Answer

Nathan MacInnes picture Nathan MacInnes · Oct 17, 2011

I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention:

The best representation of the number n as a floating point number is the string obtained from applying the JavaScript operator ToString to n.

This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then.

So, you're going to have to resort to JavaScript. This isn't straightforward because document.getElementById('numInput').value = '0.50'; still gets corrected to 0.5, so the validation isn't triggered at onchange where the default action can be prevented, it's triggered internally.

This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want:

var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
    this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
    this.setAttribute('type', 'number');
});

So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number.

If you always want the trailing 0s no matter what the user types, then you could do it something like this:

var numInput = document.getElementById('numInput');
numInput.addEventListener('blur', function () {
    if (this.value === '') {
        return;
    }
    this.setAttribute('type', 'text');
    if (this.value.indexOf('.') === -1) {
        this.value = this.value + '.00';
    }
    while (this.value.indexOf('.') > this.value.length - 3) {
        this.value = this.value + '0';
    }
});
numInput.addEventListener('focus', function () {
    this.setAttribute('type', 'number');
});

Edit: I think the second solution is more inline with what the user might expect, but it means that if the user types 0.5 it will be coerced to 0.50, so it depends if that's what you want.