[英]how to check 2 decimals? E.g. 2.2.10
how to check 2 decimals in javascript? 如何在javascript中检查2个小数? Eg 2.2.10
例如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 : 如果要检查您的字符串是否仅包含数字和点以及带尾随数字,请使用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: 如果要确定版本A是否早于版本B,则可以执行以下操作:
// 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.