Hello! There is a numeric field with a set minimum and maximum values ​​and increments of 0.5. Please tell me how to round the entered values ​​in accordance with the step.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="number" min="0" max="5" step="0.5" placeholder="1"> 

  • What does rounding mean? Display not "1", but "1.0"? - Vadim Ovchinnikov
  • and if the step is 0.3, then how should it be rounded? - lexxl
  • @lexxl, up to 0.5, I think - Igor
  • @VadimOvchinnikov, it means if the user entered 0.3 - round to 0.5 - Igor

1 answer 1

Something like this:

 var input = document.querySelector('input[type = number]'); var inputValue; var decimal = 1; input.addEventListener('change', function(e){ if(e.target.value % 1 == 0){ decimal = 0; } else { decimal = 1; } inputValue = (Math.round(e.target.value * 2) / 2).toFixed(decimal); e.target.value = inputValue; }) 
 <input type="number" min="0" max="5" step="0.5" placeholder="1"> 

  • Thank you for your reply. Is there an option to make it so that with the entered integer, the function does not process it so that at the end of change value is not rounded, i.e. didn't get ,0 at the end of the integer? - Igor
  • Added your wish in reply) - Mikl
  • Thank you for your help) - Igor