Hector Barbossa
Hector Barbossa

Reputation: 5528

javascript Number validations

I need to check if a number entered contain

1.more than two digit after decimal

2.decimal at first place (ex:.2345)

3.decimal at last place (ex:2345.)

How to do this using javascript.

Upvotes: 1

Views: 308

Answers (4)

Shakti Singh
Shakti Singh

Reputation: 86336

len = number.length;
pos = number.indexOf('.');

if (pos == 0)
{
  //decimal is at first place
}
if (pos == len - 1)
{
  //decimal is at last place
}
if (pos == len - 3)
{
  //more than two digit after decimal
}

Upvotes: 2

kzh
kzh

Reputation: 20598

function check_number(number) {
    var my_number = String(number);
    var place = my_number.indexOf(".");
    if(place == 0) return "first";
    else if(place == (my_number.length - 1)) return "last";
    else if(place == (my_number.length - 3)) return "third to last";
}

Upvotes: 1

Mark Baijens
Mark Baijens

Reputation: 13222

var number = "3.21";
if(/[0-9]{1,}\.[0-9]{2,}/.test(number)) {
  //valid
}

Upvotes: 0

aefxx
aefxx

Reputation: 25249

var reg = /\d+(?:\.\d{2,})?/;

if ( reg.test(number) )
    alert('Correct format!');

Not sure whether you'd allow decimals only (i.e. without the period) but if, that regexp should be sufficient.

Good luck.

Upvotes: 2

Related Questions