Force number entry must have two decimal places and ONLY two

How can I format the next input so that the price is forced to have two decimal places and ensure that it only allows two spaces?

So, for example, if the value is "1", it will automatically be changed to "1.00" and "1.111" will be changed to "1.11".

I've already tried step = "0.01", but it doesn't work.

JSFiddle: https://jsfiddle.net/eub68raq/ .

HTML:

<input data-number="Quantity must be a number" data-required="Unit price required" min="0" step="0.01" id="unitPrice" value="" type="number" name="unitPrice" placeholder="Unit Price"/>

      

JS I've tried: -

var number = $('input#unitPrice').val();
$('input#unitPrice').innerHTML = parseFloat(Math.round(number * 100) / 100).toFixed(2);

      

+3


source to share


3 answers


You can do it like below: -



$(document).ready(function(){
  $('input#unitPrice').blur(function(){
    var num = parseFloat($(this).val());
    var cleanNum = num.toFixed(2);
    $(this).val(cleanNum);
  });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-number="Quantity must be a number" data-required="Unit price required" min="0" step="0.01" id="unitPrice" value="" type="number" name="unitPrice" placeholder="Unit Price"/>
      

Run codeHide result


+3


source


Try the following:



parseFloat(number.toFixed(2));

      

+2


source


Using your rounding code, what you want might look like:

$(document).ready(function(){
    $('input#unitPrice').change(function(){
        $(this).val(parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2));
    });
});

      

Usage keyup

for this is not a very good choice because the user cannot change the input value. As soon as he writes something, it will be changed to 2 decimal places. If it tries to delete a digit, it will be returned.

If you want keyboard behavior, there will be a delay in adjusting the value (for example, using setInterval).

0


source







All Articles