Search code examples
javascripthtmlinputcurrency

I want my input field to always have two decimal places


For example lets say the user needs to type 112.56,

So when user types 1, input field becomes 1.00
Next when user types 1 again, input field becomes 11.00
Next when user types 2, input field becomes 112.00
Next when user types '.' (the decimal point), input field still is 112.00
Then user types 5, input field becomes 112.50
Last user types 6, and input field becomes 112.56

I've seen this achieved in my local atm machines, I'm wondering if this is achievable via html/javascript or requires a different language or a different technique

I want it to update while the user is still typing


Solution

  • document.getElementById('n').onkeyup = e => {
      const process = i => {
        let v = i.value;
        const ss = i.selectionStart;
        const resetCursor = () => i.setSelectionRange(ss,ss);
        if(/^[0]*.00$/.test(v)) {
          i.value = '';
        }
        else if(/^[0-9.]+$/.test(v)) {
          let p = v.indexOf('..');
          if(p>=0) {
            i.value = v.replace('..','.');
            resetCursor();
            process(i);
          }
          else if([...v].filter(c=>c==='.').length>1) {
            let j = v.indexOf('.');
            i.value = [...v].filter((c,k)=>k<=j||c!=='.').join('');
            resetCursor();
            process(i);
          }
          else {
            i.value = (+v).toFixed(2);    
            resetCursor();
          }
        }
        else {
          v = v.replace(/[^0-9.]/g, '');
          i.value = v;
          resetCursor();
        }
      }
      process(e.target);
    }
    <input id='n'>