使用jQuery将输入字段限制为两位小数 [英] Restrict input field to two decimals with jQuery

查看:496
本文介绍了使用jQuery将输入字段限制为两位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,我想限制,以便用户只能输入一个最多两位小数的数字。想用jQuery做这件事。

I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.

我可以用某种方式使用jQuery toFixed()函数吗?

Could I use jQuery toFixed() function somehow?

Thanx!

推荐答案

$('input#decimal').blur(function(){
    var num = parseFloat($(this).val());
    var cleanNum = num.toFixed(2);
    $(this).val(cleanNum);
    if(num/cleanNum < 1){
        $('#error').text('Please enter only 2 decimal places, we have truncated extra points');
        }
    });

这是一个小提琴 http://jsfiddle.net/sabithpocker/PD2nV/

使用 toFixed 无论如何会导致近似 123.6666 - > 123.67
如果你想避免近似检查这个答案显示两位小数,不舍入

Using toFixed will anyhow cause approximation 123.6666 -> 123.67 If you want to avoid approximation check this answer Display two decimal places, no rounding

这篇关于使用jQuery将输入字段限制为两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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