How to format a text input as a decimal in jquery

大憨熊 提交于 2019-12-11 11:23:00

问题


I have this jQuery code:

$('#amount').change(function() {
  $('#amount').val( $('#amount').val().toFixed(2) );
}); // end .change()

I need it to format the input in decmial format. Can it be done in jquery?

Example: In a text box,

if I enter 5 I want the value to be shown as 5.00

if I enter 5.1 I want the value to be shown as 5.10

if I enter 5.12 I want the value to be shown as 5.12

seems to be a simple need. I have to be missing something because I cannot imagine that javascript or jquery does not provide a function to do this.


回答1:


An elements value is always a string, and toFixed only works on numbers, so you have to convert the value to a number before you run toFixed on it

$('#amount').on('change', function() {
    this.value = parseFloat(this.value).toFixed(2);
});

FIDDLE




回答2:


Use this as the base:

Math.round(num * 100) / 100

So your code will be:

$('#amount').change(function() {
    $('#amount').val( Math.round($('#amount').val() * 100) / 100 );
});


来源:https://stackoverflow.com/questions/22820549/how-to-format-a-text-input-as-a-decimal-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!