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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With