Search code examples
javascriptinputcharacterdecimallimit

Is there a way to limit the number of decimal characters in an input when its used as a result box?


I'm making a simple html where i make calculations based on different inputs and presenting the results in other inputs using pure js.

In the below example where i divide a / b input and return the result in c,lets say you put 633 / 33 it returns a number like this : 19.181818181818183

Is there a way to make look like 19.18 ?

Using the maxlength Attribute to the result input wont work as it limits the number of characters you can type in,not the number of characters you can send to.

<input type="text" id="input1"  style="width: 100px " onkeyup='divide_numbers()'/> 
<label> / </label> 
<input type="text" id="input2"  style="width: 100px " onkeyup='divide_numbers()'/>
 <label> = </label> 
<input type="text" id="result"  style="width: 100px "/>
<script>
function divide_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value=first_number/second_number ;
}
</script>


Solution

  • You can use +number.toFixed(2), which will first create a string with two digits after the decimal point and then coerce it back to a number, removing unnecessary decimal digits.

    function add_numbers() {
      var first_number = parseFloat(document.getElementById("input1").value) ;
      var second_number = parseFloat(document.getElementById("input2").value) ;
      document.getElementById("result").value = +(first_number/second_number).toFixed(2);
    }
    <input type="text" id="input1"  style="width: 100px " onkeyup='add_numbers()'/> 
    <label> / </label> 
    <input type="text" id="input2"  style="width: 100px " onkeyup='add_numbers()'/>
     <label> = </label> 
    <input type="text" id="result"  style="width: 100px "/>