0

I have script that should convert strings to numbers when string actually is number.

First I tried isNumber(x), but it doesnt work on string that look like numbers, but actually are not, e.g. agreement number with leading zero '035859':

   if (isNumber('035859')) {
      parseFloat('035859'); //35859
   }

Next I tried parsing and comparing strings after parse and I got opposite problem - some numbers were not recognized as numbers

 if (parseFloat('2.00').toString() == '2.00') //false

What should I do to find all numbers, but skip all strings? May be someone familiar with global approach without coding all possible exceptions?

1
  • For your second example, parseFloat('2.00').toString() == '2' (integers and floats both belong to the number type in JavaScript). Commented Apr 12, 2017 at 18:59

2 Answers 2

4

parseFloat and parseInt both return NaN if the input string could not be converted to a number. You can test for NaN with the isNaN function:

var number = parseFloat( input );
if( isNaN( number ) {
    // not a number
}
else {
    // is a number
}

There's also the special-case of Infinity which you may want to test for as well:

var number = parseFloat( input );
if( !isNaN( number ) && isFinite( number ) ) {
    // is a number that is not infinity:


}

You could save trouble by having your own simple wrapper function that returns null on failure:

function getNumber( input ) {

    var number = parseFloat( input );
    if( !isNaN( number ) && isFinite( number ) ) return number;
    return null;
}

Used like so:

var number = getNumber( input );
if( number != null ) {
    // do stuff
}
Sign up to request clarification or add additional context in comments.

1 Comment

parseInt and parseFloat returns the leading numbers in case of a string which contains both leading numbers and non-string values. It returns NaN only if the first character can't be converted to number. So output of parseInt("12345L") would be 12345. Therefore, the recommended way is to use the method Number.isNaN()
1

You could design a regular expression that only matches what you regard a number (a subset of what parseFloat would convert to number):

function toNumber(s) {
    return /^-?([1-9]\d*|0)(\.\d+)?$/.test(s) ? +s : s;
}

console.log(typeof toNumber('2.00')); // number
console.log(typeof toNumber('0472638')); // string

1 Comment

Looks like that's what I was lookig for. Tests run perfect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.