英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论