Home > OS >  I want my input field to always have two decimal places
I want my input field to always have two decimal places

Time:11-06

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

CodePudding user response:

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 {
        v = (Math.floor(100*( v))/100).toFixed(2);
        i.value = v;    
        resetCursor();
      }
    }
    else {
      v = v.replace(/[^0-9.]/g, '');
      i.value = v;
      resetCursor();
    }
  }
  process(e.target);
}
<input id='n'>

CodePudding user response:

Make the input value to a Float with parseFloat. Then you can use toFixed(2) to always show 2 decimal spaces.

There is no real way around it. Use an EventListener to update it on input:

let input = document.querySelector('input');

input.addEventListener('change', function() {
  let number =  input.value;
  input.value = parseFloat(number).toFixed(2);
})
<input type="number" step="0.01" value="0">

  • Related