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.
asked Dec 8, 2010 at 13:35
Hector Barbossa
5,53813 gold badges51 silver badges70 bronze badges
-
How can a NUMBER have a decimal at the front and end? I think your meant to ask about strings.Ash Burlaczenko– Ash Burlaczenko2010年12月08日 13:37:20 +00:00Commented Dec 8, 2010 at 13:37
-
Is this part of form validation?user447356– user4473562010年12月08日 13:40:43 +00:00Commented Dec 8, 2010 at 13:40
4 Answers 4
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
}
answered Dec 8, 2010 at 13:42
Shakti Singh
86.8k21 gold badges142 silver badges156 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
jwueller
.length is a property, not a method. Nice and fast apprach, however.kzh
Probably should use else...if so as to not test multiple times.
Mark Baijens
use
pos < len - 3. Now it can have only 2 decimals.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.
answered Dec 8, 2010 at 13:40
aefxx
25.4k6 gold badges47 silver badges55 bronze badges
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";
}
answered Dec 8, 2010 at 13:43
kzh
20.8k13 gold badges77 silver badges101 bronze badges
1 Comment
kzh
@Shakti Singh, you beat me to the answer.
var number = "3.21";
if(/[0-9]{1,}\.[0-9]{2,}/.test(number)) {
//valid
}
answered Dec 8, 2010 at 13:37
Mark Baijens
13.3k11 gold badges51 silver badges77 bronze badges
4 Comments
jwueller
I think
number should be a string here. Besides that, .test() is a method of the RegExp object. You should use .match() or modify your code so that your regular expression is in front.Mark Baijens
Ah yes, thanks for pointing that out. Can you only pass a regex on strings in js?
jwueller
I am not sure if i understand what you mean, but
.match() is a method of String. You can use it to do it the other way around: "some string".match(/some/)Mark Baijens
Does it matter? Is match better compared to test?
lang-js