强制要求数字输入有两位小数且仅限于两位。

5
如何将以下输入格式化为价格,强制保留两位小数并确保只允许两位?
例如,如果值为“1”,它将自动更改为“1.00”,而“1.111”将更改为“1.11”。
我已经尝试使用step="0.01",但这不起作用。
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:

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

http://numeraljs.com/ - Dan Cantir
3个回答

7
您可以按照以下方法进行操作:

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


1
完美。正好符合需求。 - user7138187
@Nick 很高兴能帮助你:):) - Alive to die - Anant

4

试试这个:

parseFloat(number.toFixed(2));

1
使用您的代码进行四舍五入,您想要的东西可能如下所示:
$(document).ready(function(){
    $('input#unitPrice').change(function(){
        $(this).val(parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2));
    });
});

使用keyup并不是很好的选择,因为用户将无法更改输入值。一旦他写了什么,它就会被更改为2个小数位。如果他试图删除一个数字,它将被放回。
如果您想要一个键盘弹起的行为,那么纠正值将必须延迟发生(例如使用setInterval)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接