最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Force number input to have two decimal places and ONLY two - Stack Overflow

programmeradmin4浏览0评论

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: /.

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);

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/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);
Share Improve this question edited Apr 21, 2017 at 14:00 Death-is-the-real-truth 72.3k10 gold badges57 silver badges104 bronze badges asked Apr 21, 2017 at 13:18 user7138187user7138187 1
  • numeraljs. – Dan Cantir Commented Apr 21, 2017 at 13:31
Add a ment  | 

3 Answers 3

Reset to default 7

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

Try this:

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).

发布评论

评论列表(0)

  1. 暂无评论