简体   繁体   English

如何检查2位小数? 例如2.2.10

[英]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.

相关问题 如何检查浏览器是否缓存了特定资源(例如图像)? - How to check if a particular resource (e.g. image) is cached by the browser? 如何使用Javascript检查html中的父元素是否是特定的标记名(例如span) - How to check if parent element in html is specific tagname (e.g. span) using Javascript 如何检查字符串中某些字符的存在和数量(例如'x'/'X'和'o'/'O')? - How to check existence and amount of certain characters within a string (e.g. 'x'/'X' and 'o'/'O')? Firebase 资源在 blaze 计划中耗尽(例如检查配额) - Firebase resource exhausted (e.g. check quota) on blaze plan 如何检查HTML元素是否没有用JavaScript面对用户的数据(例如文本或图片)? - How to check if an HTML element has no user facing data (e.g. text or pictures) in javascript? 检查用户是否是来自 Google Analytics 的回访者(例如) - Check if user is returning visitor (e.g.) from Google Analytics 如何在Javascript中将数组显示为视觉图像(例如迷宫) - How to display arrays as visuals in Javascript (e.g. for a maze) 如何使用 MDC-Web 方法(例如 MDCIconButtonToggle) - How to use MDC-Web methods (e.g. MDCIconButtonToggle) 如何在现有语言(例如打字稿)中添加标记? - How to add a token to an existing language (e.g. typescript)? 如何使SVG元素(例如矩形)scrollIntoView? - How to make a svg element (e.g. rectangle) scrollIntoView?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM