Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make input to get only numbers with two decimal places

Currently I am using following jQuery code to filter only digits:

$('#input_field').keyup(function(e) {
    if (/\D/g.test(this.value)) {
        this.value = this.value.replace(/\D/g, '');
    }
});

But I want to get floating point numbers(upto to 2 decimal places) like this:

10.2
1.23
1000.10
like image 595
Awan Avatar asked Dec 03 '22 22:12

Awan


2 Answers

Try this regex:

/^\d+(\.\d{0,2})?$/

Your JS:

$('#input_field').keyup(function(e) {
    var regex = /^\d+(\.\d{0,2})?$/g;
    if (!regex.test(this.value)) {
        this.value = '';
    }
});
like image 50
Khanh TO Avatar answered Dec 19 '22 06:12

Khanh TO


try

toFixed(2)

eg:

var number = 2.234239;
var numberfixed=number.toFixed(2); 
like image 30
Shinov T Avatar answered Dec 19 '22 07:12

Shinov T