Restrict input field to two decimals with jQuery

javascript, jquery

Solution

$('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

Problem

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!

Original source

Related problems