Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript converting string to number only if the string is an number

Tags:

javascript

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.

like image 244
el_pup_le Avatar asked Feb 06 '26 19:02

el_pup_le


2 Answers

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; }
like image 100
Nina Scholz Avatar answered Feb 09 '26 08:02

Nina Scholz


var str = "";
var num = isNaN( Number(str) ) ? str : Number(str);
like image 20
Mohit Bhardwaj Avatar answered Feb 09 '26 07:02

Mohit Bhardwaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!