Ismailp Ismailp -4 years ago 67
Javascript Question

Restrict input field to two decimals with 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.

Could I use jQuery toFixed() function somehow?

Thanx!

Answer Source
$('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');
        }
    });

Here is a fiddle http://jsfiddle.net/sabithpocker/PD2nV/

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download