Home  >  Article  >  Web Front-end  >  How to Check for Numeric Values in Pure JavaScript: An Alternative to jQuery\'s isNumeric()?

How to Check for Numeric Values in Pure JavaScript: An Alternative to jQuery\'s isNumeric()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 16:57:02648browse

How to Check for Numeric Values in Pure JavaScript: An Alternative to jQuery's isNumeric()?

Checking Numerical Values in Pure JavaScript: A jQuery isNumeric() Equivalent

In contrast to jQuery's isNumeric() function for testing numeric integrity, pure JavaScript lacks a direct equivalent. However, you can create a custom isNumeric() function to fill this void:

<code class="javascript">function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}</code>

This function combines the parseFloat() and isFinite() methods to accurately determine the numeric nature of values.

Cautionary Note

Avoid using parseInt() to check for numerics, as it's not a reliable method due to its potential to convert non-numeric strings (e.g., "12px") to numerical values.

The above is the detailed content of How to Check for Numeric Values in Pure JavaScript: An Alternative to jQuery\'s isNumeric()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn