简体   繁体   English

如何检查字符串/数字是否为简单数字

[英]How to check if string/number is SIMPLE number

In most cases for me, i just want to check if string/number that i get is simple number only like this:在大多数情况下,对我来说,我只想检查我得到的字符串/数字是否只是这样的简单数字:

0, 1, 500, -1, 1.1, -1.1, 1.1013200 and so on. 0、1、500、-1、1.1、-1.1、1.1013200 等等。

And then convert it safely, without getting unexpected results.然后安全地转换它,而不会得到意想不到的结果。

What will be correct way to check if string or number is SIMPLE number?检查字符串或数字是否为简单数字的正确方法是什么?

Simple stands for:简单代表:

  1. No scientific notations like "1e+30"没有像“1e+30”这样的科学记数法
  2. No spaces like " 1"没有像“1”这样的空格
  3. No ".1" or "080" and notations like this没有“.1”或“080”和这样的符号
  4. Limit to length that js can handle, convert to and from with same result限制 js 可以处理的长度,来回转换结果相同
  5. Other stuff that i could forget其他我可以忘记的东西

Codesandbox . 代码沙盒

You can parse it to number and parse this number to String another time.您可以将其解析为数字,然后再将此数字解析为字符串。 After test if the two variables is the same.测试两个变量是否相同后。

For scientific notations you can check if the string includes "e" or includes "NaN" for NaN number对于科学记数法,您可以检查字符串是否包含“e”或包含“NaN”作为NaN数字

Like:像:

 var num_s = " 898"; var num_n = Number(num_s) var num2_s = "89.8"; var num2_n = Number(num2_s) var num3_s = "1e+23"; var num3_n = Number(num3_s) var num4_s = "NaN"; var num4_n = Number(num4_s) console.log(num_s === String(num_n)) console.log(num2_s === String(num2_n)) console.log(num3_s === String(num3_n) &&.num3_s.includes('e')) console.log(num4_s === String(num4_n) && !num4_s.includes('NaN'))

You can create a function that test this cases like您可以创建一个函数来测试这种情况,例如

function isSimpleNumber(num_s) {
  var num_n = Number(num_s)
  if (Number.isNaN(num_n) || num_n > Number.MAX_SAFE_INTEGER || num_n < Number.MIN_SAFE_INTEGER) 
    return false;
  return num_s === String(num_n) && !num_s.includes('e');
}

A somewhat "dumb" solution but you can convert the input to a number and check if it looks like the input again:一个有点“愚蠢”的解决方案,但您可以将输入转换为数字并再次检查它是否看起来像输入:

 function canSafelyConvert(input) { //convert to number const numeric = Number(input); //cannot convert if (Number.isNaN(numeric)) return false; //discard values that are going to cause problems if (numeric > Number.MAX_SAFE_INTEGER || numeric < Number.MIN_SAFE_INTEGER) return false; let canonicalValue = input; if(canonicalValue.includes(".")) { //remove trailing zeries and the decimal dot, if nothing is left after it canonicalValue = canonicalValue.replace(/\.?0+$/g, "") } //check if the converted value seems the same as the input return String(numeric) === canonicalValue; } const testValues = [ //valid "0", "1", "1.000", "500", "-1", "1.1", "-1.1", "1.1013200", //invalid "1e+30", " 1", "080", ".1" ] for (const value of testValues) { console.log(value, ":", canSafelyConvert(value)); }

This will filter out any values that are different when converted to a JavaScript numeric.这将过滤掉转换为 JavaScript 数字时不同的任何值。

  1. If a value simply cannot be converted, then NaN would be produced and you can safely discard the output.如果一个值根本无法转换,则会产生NaN ,您可以安全地丢弃输出。
  2. If the value is too small or too large, then it can be discarded as it's not going to be safe to use.如果该值太小或太大,则可以将其丢弃,因为使用起来不安全。
  3. If the output seems OK, then you can compare it to the input again.如果输出看起来没问题,那么您可以再次将其与输入进行比较。 You have to strip trailing zeroes after the decimal, since 1.2000 will be converted to 1.2 .您必须去除小数点后的尾随零,因为1.2000将转换为1.2 You also have to strip a dangling decimal dot for the case where you get 1.000 which converts to 1 .如果您得到1.000转换为1 ,您还必须去除悬空的小数点。

This will include some that aren't actually different, eg, Number(".1") would produce 0.1 which is the correct conversion but it's explicitly mentioned to be incorrect.包括一些实际上没有区别的内容,例如, Number(".1")会产生0.1 ,这是正确的转换,但它被明确提到是不正确的。

Thanks to @Vlaz and R3tep i combined a function to make it work, only problem is.1 values, but cannot see a way to check it and they converted to and from without problems, it's ok.感谢@Vlaz 和 R3tep,我组合了一个函数使其工作,唯一的问题是 .1 值,但看不到检查它的方法,并且它们可以毫无问题地来回转换,没关系。

Codesandbox .代码沙盒

const isSimpleNum = n => {
  const nStr = String(n);
  const nNum = Number(n);

  if (nStr === "-0") return true;

  if (nNum > Number.MAX_SAFE_INTEGER || nNum < Number.MIN_SAFE_INTEGER)
    return false;

  if (nStr === String(nNum) && !["e", "NaN"].some(e => nStr.includes(e))) {
    return true;
  } else {
    return false;
  }
};

const isTrue = ["1", "-1", 1, -1, 0, -0, "0", "-0", 1.1, -0.1, "0.1", "-0.1"];
const isFalse = [
  "-0,1",
  "080",
  0.1,
  ".1",
  " 898",
  "a",
  "1e+23",
  "NaN",
  undefined,
  null,
  NaN,
  Infinity
];

isTrue.forEach((v, i) => {
  if (!isSimpleNum(v)) {
    console.log(`isTrue index ${i} as ${v} not passed`);
  }
});
console.log("isTrue done");

isFalse.forEach((v, i) => {
  if (isSimpleNum(v)) {
    console.log(`isFalse index ${i} as ${v} not passed`);
  }
});
console.log("isFalse done");

Using regular expression and Number.MAX_SAFE_INTEGER使用正则表达式和Number.MAX_SAFE_INTEGER

 let num = '090071'; const regx = /(^0$)|(^[1-9][0-9.-]{1,}$)/; console.log(regx.test(num) && Number(num) <= Number.MAX_SAFE_INTEGER)

Simply make a Regex check:只需进行正则表达式检查:

var reg = /^(0|-?[1-9]\d*\.?\d+)$/;

var value1 = '1e+30';
var value2 = ' 1';
var value3 = '.1';
var value4 = '01';

var value5 = '123';
var value6 = '1.2';
var value7 = '-1.2';

var reg = /^(0|-?[1-9]\d*\.?\d+)$/;

// This should be false
console.log(reg.test(value1))

// This should be false
console.log(reg.test(value2))

// This should be false
console.log(reg.test(value3))

// This should be false
console.log(reg.test(value4))

// This should be true
console.log(reg.test(value5))

// This should be true
console.log(reg.test(value6))

// This should be true
console.log(reg.test(value7))
  • -? for 0 or 1 '-' Character对于 0 或 1 个 '-' 字符
  • \d+ for 1 or more numbers \d+表示 1 个或多个数字
  • \.? for 0 or 1 decimal seperator对于 0 或 1 个小数点分隔符

For more information there is a good documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp有关更多信息,这里有一个很好的文档: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM