简体   繁体   中英

Force number input to have two decimal places and ONLY two

How can I format the following input for a price to be forced to have two decimal places and ensure that it allows only two places?

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

I've already tried step="0.01", but this won'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);

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"/> 

尝试这个:

parseFloat(number.toFixed(2));

Using your code for rounding, the thing you want could look like this:

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

Using keyup for this isn't very lucky choice because the user will not be able to change the input value. As soon as he writes something it will be changed to 2 decimal places. If he tries to delete a digit it will be put back.

If you want a keyup behavior, then correcting the value will have to happen with a delay (by using setInterval for example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM