Javascript 仅当字符串是数字时才将字符串转换为数字

问题描述 投票:0回答:7

如果我不知道字符串值是否是有效数字,如何将字符串转换为数字。我想保留该字符串,就好像它无效一样。

示例

"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
作为值可能是一个坏主意,并且只保留字符串原样会更好。

javascript
7个回答
4
投票

您可以检查字符串数值是否等于该值。

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; }


3
投票
var str = "";
var num = isNaN( Number(str) ) ? str : Number(str);

2
投票

您需要先进行一些简单的检查,然后使用

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(" "));   //" "

2
投票

您可以创建自定义函数

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"));


0
投票

您可以使用

==
来检查转换后的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
}

0
投票

利用“||”如下操作符

var num = parseInt(str) ||数字;

如果有效,它将返回相当于“str”的整数,否则保持原样。


0
投票

我想出的最短的表达方式:

+n || n == 0 ? +n : n

简约优雅。

© www.soinside.com 2019 - 2024. All rights reserved.