How to 'push' digits to the left in an input?

Viewed 193

I've seen this done on other websites before, and I've been googling more than an hour and can't seem to find what I'm trying to do. Essentially;

When a visitor types "1" into the input, the input formats it as 0.01

Then they type "0", which becomes 0.10

Then another "0", which becomes 1.00

So each number they type sort of 'fills in' from the right, preserving two decimal places. How to do that?

1 Answers

This will do it (now even with deleting chars),

document.getElementById('inp').addEventListener('input', function() {
    if (isNaN(this.value))
        return;
    this.value = this.value.replace('.','');
    if (this.value.length==1) {
        this.value = '0.0' + this.value;
    } else if (this.value.length==2) {
        this.value = '0.' + this.value;
    } else {
        this.value =  +this.value.slice(0,-2) +'.' + this.value.substr(-2);
    }
});
<input id='inp'>

Related