开发者

how to check 2 decimals? E.g. 2.2.10

开发者 https://www.devze.com 2022-12-26 09:42 出处:网络
how to check 2 decimals 开发者_运维知识库in javascript? E.g. 2.2.10You have to treat it as a string (it isn\'t a number) and a regular expression is probably the easiest way to achieve this:

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 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


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消