Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 411
Ismailp Avatar asked May 13 '12 09:05

Ismailp


People also ask

How do I get two decimal places in jQuery?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.

How do you limit decimal places to 2?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do I get 2 decimal places in JavaScript?

Syntax. number. toFixed(2); In the above syntax toFixed() is the method of formatting a number with twoIn the above syntax toFixed() is the method of formatting a number with two decimals in JavaScript and number is the number to be formatted with two decimals.


2 Answers

An alternative approach with a regular expression:

    $('#id').on('input', function () {
        this.value = this.value.match(/^\d+\.?\d{0,2}/);
    });

The id selector can be replaced by a css selector.

like image 80
Tegge Avatar answered Oct 11 '22 15:10

Tegge


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

like image 36
sabithpocker Avatar answered Oct 11 '22 15:10

sabithpocker