how to check 2 decimals in javascript? E.g. 2.2.10
You have to treat it as a string (it isn't a number) and a regular expression is probably the easiest way to achieve this:
'2.2.10'.match(/^\d+\.\d+\.\d+$/);
Alternatively, if you assume that everything else is a digit anyway:
'2.d2.10'.split('.').length === 3
If you're trying to determine whether version A is before version B, you could do something like this:
// Assumes "low" numbers of tokens and each token < 1000
function unversion(s) {
var tokens = s.split('.');
var total = 0;
$.each(tokens, function(i, token) {
total += Number(token) * Math.pow(0.001, i);
});
return total;
}
// that version b is after version a
function isAfter(a, b) {
return unversion(a) < unversion(b);
}
Thanks David.
It helped me a lot. If i use this (/^\d+.\d+.\d+$/) reg. exp., it results for only two decimals. But if I want only 2 or 2.1 or 2.2.2.1, there should be a generic regular exp. for displaying any kind of such expressions.
I have used 'or' expression also,but that results in alpha-numeric. I want only numbers in the expression. Is it possible?
Thanks in advance.
If you want to check whether your string contains only digits and dots, with a trailing number, here is a regexp :
if(myString.match(/^[\d\.]*\d$/)) {
// passes the test
}
"2".match(/^[\d\.]*\d$/) // true
"2.2".match(/^[\d\.]*\d$/) // true
"2.2.10".match(/^[\d\.]*\d$/) // true
".2".match(/^[\d\.]*\d$/) // true
"2.".match(/^[\d\.]*\d$/) // FALSE
"fubar".match(/^[\d\.]*\d$/) // FALSE