[英]Javascript converting string to number only if the string is an number
如果我不知道字符串值是否为有效数字,如何将字符串转换为数字。 如果它无效,我想保留字符串。
例
"0" -> 0
"0.5" -> 0.5
"100" -> 100
"abc" -> "abc" // remains a string
" " -> " " // remains an empty string
"-1" -> -1 // I'd like to convert negative numbers too
我试过了
var str = " ";
var num = +str // num = 0
var num = Number(str) // num = 0
var num = parseInt(str) // num = NaN
所以我的问题似乎是空间问题。 我正在考虑使用parseInt
但我认为在Javascript中使用NaN
作为值可能是一个坏主意,只是将字符串保留为更好。
您可以检查弦乐数值是否等于该值。
var array = ["0", "0.5", "100", "abc", " "]; console.log(array.map(a => (+a).toString() === a ? +a : a));
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以创建自定义功能
function customParseInt(str) { const parsed = +str; return str.trim()==="" ? str : isNaN(parsed) ? str : parsed; } console.log(customParseInt("0")); console.log(customParseInt("0.5")); console.log(customParseInt("100")); console.log(customParseInt("abc")); console.log(customParseInt(" ")); console.log(customParseInt("5ab")); console.log(customParseInt("-1"));
var str = "";
var num = isNaN( Number(str) ) ? str : Number(str);
您可以使用==
来检查转换后的int和字符串是否相同。
例如,你有2个字符串
var a = '123', b = '111x';
var intA = parseInt(a), intB = parseInt(b);
if(a == intA){
console.log(a is a valid integer string); // this gets printed
}else{
console.log('a is not a valid integer string');
}
if(b == intB){
console.log(b is a valid integer string);
}else{
console.log('b is not a valid integer string');// this gets printed
}
利用'||' 运营商如下
var num = parseInt(str)|| NUM;
如果有效,它将返回整数等效的'str',否则保持原样。
您需要先进行一些简单的检查,然后使用Number(x)
,因为它将处理小数点数等等。 正如名称所暗示的那样, parseInt
只处理整数。
这是一个例子。
function toNumberIfNumber(convertee) {
const prep = convertee.trim();
if (prep === "") {
return convertee;
}
const num = Number(convertee);
if (isNaN(num)) {
return convertee;
} else {
return num;
}
}
console.log(toNumberIfNumber("0")); //0
console.log(toNumberIfNumber("0.5")); //0.5
console.log(toNumberIfNumber("100")); //100
console.log(toNumberIfNumber("abc")); //"abc"
console.log(toNumberIfNumber(" ")); //" "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.