如何在jQuery中将文本输入格式化为小数 [英] How to format a text input as a decimal in jquery

查看:349
本文介绍了如何在jQuery中将文本输入格式化为小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个jQuery代码:

I have this jQuery code:

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

我需要它以decmial格式格式化输入.可以在jquery中完成吗?

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

示例: 在文本框中,

如果输入5,我希望该值显示为5.00

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

如果输入5.1,我希望该值显示为5.10

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

如果我输入5.12,我希望该值显示为5.12

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

似乎很简单.我必须缺少一些东西,因为我无法想象javascript或jquery没有提供执行此操作的功能.

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.

推荐答案

元素值始终是字符串,并且toFixed仅适用于数字,因此在运行toFixed之前必须将值转换为数字在上面

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

这篇关于如何在jQuery中将文本输入格式化为小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆