[ACCEPTED]-Check if a variable contains a numerical value in Javascript?-javascript
What about:
function isNumber(n){
return typeof(n) != "boolean" && !isNaN(n);
}
The isNaN built-in function is used 7 to check if a value is not a number.
Update: Christoph 6 is right, in JavaScript Boolean types are 5 convertible to Number, returning the 1 for 4 true and 0 for false, so if you evaluate 3 1 + true
the result will be 2.
Considering this behavior 2 I've updated the function to prevent converting 1 boolean values to its numeric representation.
I don't think any of the suggestions till 22 now actually work. Eg
!isNaN(parseFloat(foo))
doesn't because parseFloat()
ignores 21 trailing non-numeric characters.
To work 20 around this, you could compare the returned 19 value to the one returned by a cast via 18 Number()
(or equivalently by using unary +
, but I 17 prefer explicit casting):
parseFloat(foo) === Number(foo)
This will still 16 work if both functions return NaN
because NaN !== NaN
is 15 true
.
Another possibility would be to first cast 14 to string, then to number and then check 13 for NaN
, ie
!isNaN(Number(String(foo)))
or equivalently, but less readable 12 (but most likely faster)
!isNaN(+('' + foo))
If you want to exclude 11 infinity values, use isFinite()
instead of !isNaN()
, ie
isFinite(Number(String(foo)))
The 10 explicit cast via Number()
is actually unnecessary, because 9 isNan()
and isFinite()
cast to number implicitly - that's 8 the reason why !isNaN()
doesn't work!
In my opinion, the 7 most appropriate solution therefore would 6 be
isFinite(String(foo))
As Matthew pointed out, the second approach 5 does not handle strings that only contain 4 whitespace correctly.
It's not hard to fix 3 - use the code from Matthew's comment or
isFinite(String(foo).trim() || NaN)
You'll 2 have to decide if that's still nicer than 1 comparing the results of parseFloat()
and Number()
.
To check types in javascript you can use 9 the typeof
operator:
js> var x = 1;
js> typeof(x);
number
So:
if (typeof(x) === 'number') {
// Do something
}
If you want to coerce the 8 value of a variable to an integer, you can 7 use parseInt(x, 10)
which will parse the value as an integer 6 in base 10. Similarly, you can use parseFloat
if 5 you want a floating point value. However, these 4 will always coerce regardless of type so 3 passing null
, true
, etc will always return a number. However, you 2 can check whether its a valid number by 1 calling isNaN
.
So, putting it 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));
}
This checks for numerical values, including 3 negative and floating point numbers.
function is_numeric(val){
return val && /^-?\d+(\.\d+)?$/.test(val + '');
}
@Vordreller: I 2 corrected the Regex. It should work properly 1 now.
function is_numeric(val) {
return ((+val) == val);
}
That should do the trick.
0
Here's what I came up with:
value = "2.34";
if (parseFloat(value).toString() === value) {
alert("number");
}
This should work 6 with floats and ints, positive and negative. I 5 don't know about infinity, as some of the 4 answers above have discussed.
If your value 3 might actually be a number and not always 2 a string, you can change the === to a == and 1 it will handle both.
Here's some benchmarks for isNaN vs. isFinite 3 and typeof === "number"
http://jsperf.com/isnan-vs-isfinite-vs/3
Apparently 2 typeof === "number" is roughly 1 5 times faster
Run the code snippet to see comparisons 6 of top answers on this topic.
Some test 5 cases are not highlighted (and don't contribute 4 to the summary). These cases are flagged 3 as ambiguous because it is not clear whether 2 a given value should or should not be considered 1 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>
Here is my Solution : ES6/2015
Disclaimer: This solution works only if user send a Number Type as an input. For Example: 23 is a number type but '23' is not a number type it is a String Type.
function isValidNumber(value) {
return typeof value === 'number' && Number.isNaN(value) === false;
}
Test Cases
isValidNumber(10) // true
isValidNumber(10.34) // true
isValidNumber('geo10') // false
isValidNumber('10geo') // false
isValidNumber('') // false
isValidNumber(NaN) // false
isValidNumber(true) // false
isValidNumber(false) // false
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.