Check if a variable contains a numeric value in Javascript?

In PHP, it's pretty simple:

is_numeric(23);//true is_numeric("23");//true is_numeric(23.5);//true is_numeric(true);//false 

But how to do it in Javascript? I could use regex, but is there a function for this?

+11
javascript
Mar 01 '09 at 23:10
source share
8 answers

What about:

 function isNumber(n){ return typeof(n) != "boolean" && !isNaN(n); } 

The isNaN function is used to check if a value is not a number.

Update: Christophe is right, in JavaScript, Boolean types are converted to Number, returning a value of 1 for true and 0 for false, so if you evaluate to 1 + true , the result will be 2.

Given this behavior, I updated the function to prevent the conversion of Boolean values ​​to numeric representation.

+23
Mar 01 '09 at 23:18
source share

I don’t think any suggestions still really work. For example,

 !isNaN(parseFloat(foo)) 

not because parseFloat() ignores trailing non-numeric characters.

To get around this, you can compare the return value with that returned with Number() (or, equivalently, with unary + , but I prefer casting explicitly):

 parseFloat(foo) === Number(foo) 

This will work if both functions return NaN , because NaN !== NaN is true .

Another possibility would be to first pass to the string, then to the number, and then check for NaN , i.e.

 !isNaN(Number(String(foo))) 

or equivalent, but less readable (but most likely faster)

 !isNaN(+('' + foo)) 

If you want to exclude infinity values, use isFinite() instead of !isNaN() , i.e.

 isFinite(Number(String(foo))) 

Explicit listing via Number() is not really needed, because isNan() and isFinite() not accurately indicate the number - the reason !isNaN() does not work!

In my opinion, the most appropriate solution would be

 isFinite(String(foo)) 



As Matthew noted, the second approach does not process strings that contain only spaces.

It's not hard to fix - use the code from Matthew's comment

 isFinite(String(foo).trim() || NaN) 

You will need to decide how much better this is than comparing the results of parseFloat() and Number() .

+14
Mar 02 '09 at 10:25
source share

To test types in javascript, you can use the typeof operator:

 js> var x = 1; js> typeof(x); number 

So:

 if (typeof(x) === 'number') { // Do something } 

If you want to force the value of the variable to an integer, you can use parseInt(x, 10) , which will parse the value as an integer in base 10. Similarly, you can use parseFloat if you want to have a floating point value, however they always will be forced regardless of type, so passing null , true , etc. Will always return a number. However, you can check if its valid number is valid by calling isNaN .

So, all together:

 !isNaN(parseFloat(23)) // true !isNaN(parseFloat('23')) // true !isNaN(parseFloat(23.5)) // true !isNaN(parseFloat(true)) // false 

or

 function isNumber(x) { return !isNaN(parseFloat(x)); } 
+5
Mar 01 '09 at 23:19
source share

This checks for numerical values, including negative numbers and floating point numbers.

 function is_numeric(val){ return val && /^-?\d+(\.\d+)?$/.test(val + ''); } 



@Vordreller: I fixed Regex. Now it should work correctly.

+3
Mar 01 '09 at 23:16
source share
 function is_numeric(val) { return ((+val) == val); } 

That should do the trick.

+1
Mar 01 '09 at 23:16
source share

Here is what I came up with:

 value = "2.34"; if (parseFloat(value).toString() === value) { alert("number"); } 

This should work with float and ints, positive and negative. I do not know about infinity, as some of the above answers discussed.

If your value can really be a number and not always a string, you can change === to a == and it will handle both.

0
Dec 15 '12 at 2:27
source share

Here are some tests for isNaN vs. isFinite and typeof === "number"

http://jsperf.com/isnan-vs-isfinite-vs/3

Apparently typeof === "number" is about 5 times faster

0
Jul 18 '14 at 23:41
source share

Run the code snippet to see a comparison of the best answers on this topic.

Some test cases do not stand out (and do not contribute to the summary). These cases are labeled ambiguous because it is not clear whether this value should be considered or not considered a number.

 // Each of these functions should output a truthy/falsy value if the input is // a number const solutionsToTest = [ v => parseFloat(v), v => Number(v), v => !isNaN(v), v => typeof v != "boolean" && !isNaN(v), v => isFinite(String(v)), v => !isNaN(parseFloat(v)) && isFinite(v) ]; const testCases = [ //[ Test Name, Test Value, Expected Output, Is Ambiguous ] // Whitespace ['""', "", false, false], ['"\\t"', "\t", false, false], ['" "', " ", false, false], // Infinity ['"Infinity"', "Infinity", false, true], ['"+Infinity"', "Infinity", false, true], ["-Infinity", -Infinity, false, true], ["Infinity", Infinity, false, true], // Numbers mixed with symbols ['"123abc"', "123abc", false, true], ['"abc123"', "abc123", false, false], ['".0."', ".0.", false, false], ['"1."', "1.", true, true], ['"."', ".", false, true], ['"01"', "01", true, true], ['"-0"', "-0", true, true], ["+1", +1, true, true], ["-1", -1, true, true], // Other js types ["'null'", "null", false, false], ["'true'", "true", false, false], ["'false'", "false", false, false], ["null", null, false, false], ["true", true, false, false], ["false", false, false, false], ["NaN", NaN, false, false], ["[]", [], false, false], ["{}", {}, false, false], ["/./", /./, false, false], ["() => {}", () => {}, false, false] ]; const styles = { code: { fontFamily: "monospace", fontSize: 16 }, success: { backgroundColor: "#00ff5478" }, failure: { backgroundColor: "#ff00008c" } }; class TestCaseTable extends React.Component { static renderTableHeader(solutionsToTest) { return ( <tr> <th> <p>Test Case</p> </th> {solutionsToTest.map(f => ( <th key={f.toString()}> <p style={styles.code}>{f.toString()}</p> </th> ))} </tr> ); } static renderTableRow(testCase, solutionsToTest) { const [testName, input, expectedOutput, isAmbiguous] = testCase; return ( <tr key={testName}> <td style={styles.code}>{testName}</td> {solutionsToTest.map(f => { const output = Boolean(f(input)); const style = isAmbiguous ? {} : output == expectedOutput ? styles.success : styles.failure; return ( <td style={style} key={f.toString()}> <p>{output + ""}</p> </td> ); })} </tr> ); } render() { // Sort test cases, put the ambiguous ones after (but maintain stable sort // order) let sortedCases = [ ...testCases.filter(([a, b, c, ambiguous]) => !ambiguous), ...testCases.filter(([a, b, c, ambiguous]) => ambiguous) ]; return ( <table> <thead>{TestCaseTable.renderTableHeader(solutionsToTest)}</thead> <tbody> {sortedCases.map(tc => TestCaseTable.renderTableRow(tc, solutionsToTest) )} </tbody> </table> ); } } class TestCaseSummaryTable extends React.Component { renderTableHeader(solutionsToTest) { return ( <tr> <th>Summary</th> {solutionsToTest.map(f => ( <th key={f.toString()}> <p style={styles.code}>{f.toString()}</p> </th> ))} </tr> ); } renderSuccessRateRow(solutionsToTest, testCases) { // Ignore potentially ambiguous test cases testCases = testCases.filter( ([name, input, expected, ambiguous]) => !ambiguous ); const numSuccess = testSolution => testCases.reduce((succeeded, [name, input, expected]) => { return succeeded + (Boolean(testSolution(input)) == expected ? 1 : 0); }, 0); return ( <tr> <td> <p>Test Success</p> </td> {solutionsToTest.map(f => ( <td> <p> {numSuccess(f)} / {testCases.length} </p> </td> ))} </tr> ); } render() { return ( <table> <thead>{this.renderTableHeader(solutionsToTest)}</thead> <tbody>{this.renderSuccessRateRow(solutionsToTest, testCases)}</tbody> </table> ); } } const root = () => { return ( <div> <TestCaseSummaryTable /> <TestCaseTable /> </div> ); }; ReactDOM.render(root(), document.querySelector("#application")); 
 td { text-align: center; vertical-align: middle; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="application"></div> 
0
Jan 31 '18 at 21:55
source share



All Articles