如何检查未知值是否是有效的数字?

huangapple go评论82阅读模式
英文:

How to check if unknown value is a valid number?

问题

给定一个类型为 unknown 的值和一个描述该值必须是整数或浮点数值的配置。我从这个函数开始:

function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
  if (Number.isNaN(value)) {
    return false;
  }
  
  if (!isAcceptingFloatingPointNumbers) {
    return Number.isInteger(value);
  }
  
  return true;
}

问题在于,当我像这样调用函数时:

isValueNumber("this is not a valid number", true)

它仍然返回 true,因为我的检查 Number.isNaN 不正确(https://stackoverflow.com/questions/25176459/is-number-isnan-more-broken-than-isnan)。

你有没有任何想法如何修复这个验证函数?

英文:

Given a value of type unknown and a configuration describing if that value must be an integer or float value. I started with this function

function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
  if (Number.isNaN(value)) {
    return false;
  }
  
  if (!isAcceptingFloatingPointNumbers) {
    return Number.isInteger(value);
  }
  
  return true;
}

The problem is that when I call the function like so

isValueNumber("this is not a valid number", true)

it still returns true because my check Number.isNaN is not correct ( https://stackoverflow.com/questions/25176459/is-number-isnan-more-broken-than-isnan )

Do you have any ideas how to fix this validator function?

答案1

得分: 2

这样,如果不是一个 number,该函数将返回 false:

function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
  if (typeof value !== 'number') {
    return false;
  }
  
  if (!isAcceptingFloatingPointNumbers) {
    return Number.isInteger(value);
  }
  
  return true;
}
英文:

This way, the function will return false if not a number :

function isValueNumber(value: unknown, isAcceptingFloatingPointNumbers: boolean) {
  if (typeof value !== 'number') {
    return false;
  }
  
  if (!isAcceptingFloatingPointNumbers) {
    return Number.isInteger(value);
  }
  
  return true;
}

huangapple
  • 本文由 发表于 2023年1月9日 17:12:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055123.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定