最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript converting string to number only if the string is an number - Stack Overflow

programmeradmin0浏览0评论

How can I convert string to a number if I don't know if the string value is a valid number or not. I want to leave the string as is if it is not valid.

Example

"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

I've tried

var str = " ";
var num = +str // num = 0
var num = Number(str) // num = 0
var num = parseInt(str) // num = NaN

So seems my problem is with space. I was thinking of using parseInt but I thought that it might be a bad idea to use NaN as a value in Javascript and just leaving the string as is would be better.

How can I convert string to a number if I don't know if the string value is a valid number or not. I want to leave the string as is if it is not valid.

Example

"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

I've tried

var str = " ";
var num = +str // num = 0
var num = Number(str) // num = 0
var num = parseInt(str) // num = NaN

So seems my problem is with space. I was thinking of using parseInt but I thought that it might be a bad idea to use NaN as a value in Javascript and just leaving the string as is would be better.

Share Improve this question edited May 30, 2017 at 9:47 el_pup_le asked May 30, 2017 at 9:31 el_pup_leel_pup_le 12.2k26 gold badges90 silver badges146 bronze badges 3
  • 5 Create a custom function that will use parseInt. If the result is NaN you return the string – Weedoze Commented May 30, 2017 at 9:32
  • 1 you can add a simple if condition. no? – Mohit Bhardwaj Commented May 30, 2017 at 9:32
  • 1 0.5 isn't an int...? – evolutionxbox Commented May 30, 2017 at 9:36
Add a ment  | 

7 Answers 7

Reset to default 4

You could check if the stringed numerical value is equal to the value.

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

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

You need to do some simple checking first, then use the Number(x) as it will handle decimal point numbers and more. parseInt only deals with, as the name implies, integers.

Here is an example.

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

You can create a custom function

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

You can use == to check if the converted int and the string are same.

for example you have 2 strings

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
}

Make use of '||' operator like below

var num = parseInt(str) || num;

It will return integer equivalent of 'str' if valid otherwise leaves it as it is.

The shortest expression I've came up with:

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

Simple & elegant.

发布评论

评论列表(0)

  1. 暂无评论