Skip to content
Fix Code Error

(Built-in) way in JavaScript to check if a string is a valid number

March 13, 2021 by Code Error
Posted By: Electrons_Ahoy

I’m hoping there’s something in the same conceptual space as the old VB6 IsNumeric() function?

Solution

2nd October 2020: note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point ".":

function isNumeric(str) {
  if (typeof str != "string") return false // we only process strings!  
  return !isNaN(str) && // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}

To check if a variable (including a string) is a number, check if it is not a number:

This works regardless of whether the variable content is a string or number.

isNaN(num)         // returns true if the variable does NOT contain a valid number

Examples

isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true

Of course, you can negate this if you need to. For example, to implement the IsNumeric example you gave:

function isNumeric(num){
  return !isNaN(num)
}

To convert a string containing a number into a number:

Only works if the string only contains numeric characters, else it returns NaN.

+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters

Examples

+'12'              // 12
+'12.'             // 12
+'12..'            // NaN
+'.12'             // 0.12
+'..12'            // NaN
+'foo'             // NaN
+'12px'            // NaN

To convert a string loosely to a number

Useful for converting ’12px’ to 12, for example:

parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.

Examples

parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last two may be different
parseInt('12a5')   // 12       from what you expected to see. 

Floats

Bear in mind that, unlike +num, parseInt (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use parseInt() because of this behaviour, you’re probably better off using another method instead):

+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12

Empty strings

Empty strings may be a little counter-intuitive. +num converts empty strings or strings with spaces to zero, and isNaN() assumes the same:

+''                // 0
+'   '             // 0
isNaN('')          // false
isNaN('   ')       // false

But parseInt() does not agree:

parseInt('')       // NaN
parseInt('   ')    // NaN
Answered By: Dan

Related Articles

  • Pandas: Get Grouped and Conditioned Last Value
  • How do I vectorize a Pandas function that counts…
  • How do I record if a value has been previously seen…
  • Validate decimal numbers in JavaScript - IsNumeric()
  • Is CSS Turing complete?
  • How to convert Hour: minutes: seconds to decimal number in R
  • late event seems not being dropped when doing…
  • Generate new observations based on IF statement R
  • Sequential occurrence (advanced gaps and islands problem)
  • Installation of VB6 on Windows 7 / 8 / 10
  • How can I turn the unique values of a column into…
  • IsNumeric gives unexpected results in excel/vba for…
  • How not to get a repeated attribute of an object?
  • Validate that a string is a positive integer
  • How to convert time format in numeric in R
  • How can I format a decimal to always show 2 decimal places?
  • Remove leading zeros from a number in Javascript
  • Detecting when Partial extends T
  • What does this symbol mean in JavaScript?
  • Dodged bar plot in R based on to columns with count…
  • How to find the overall top played game name by each…
  • How do I include certain conditions in SQL Count
  • What are the best JVM settings for Eclipse?
  • Python: Float to Decimal conversion and subsequent…
  • Subtract three rows from an array in angular 7
  • SQL Query : Add values to columns based on other columns
  • Problems Installing CRA & NextJS from NPM…
  • easiest way to extract Oracle form xml format data
  • Issue with iron-ajax request
  • How to retain value and compute based on group of…
  • How to do, each row grouping and get previous date's…
  • How to save all repeated loop results in R in a dataframe
  • javascript .replace and .trim not working in vuejs
  • Using Excel to GROUP BY and find date WHERE MAX
  • Partition a Dataset according to the Min & Max…
  • How do I manipulate a Dataframe with Pivot_Table in Python
  • Understanding implicit in Scala
  • Rolling Average Home and Away
  • Pandas: Looking back in time
  • Adding condition to existing function
  • What does "Fatal error: Unexpectedly found nil while…
  • Design DFA accepting binary strings divisible by a…
  • What are the undocumented features and limitations…
  • First week of year considering the first day last year
  • How to calculate Cohen's D across 50 points in R
  • Reference - What does this regex mean?
  • How do you use "git --bare init" repository?
  • How do the PHP equality (== double equals) and…
  • Unexpected end of JSON input while parsing
  • Playing with a Pandas Dataframe with Time Column
  • How to get the date a status changes in a time series?
  • Running a cron every 30 seconds
  • pyspark window function from current row to a row…
  • Joining and comparing values of one df with first…
  • Finding all possible combinations of numbers to…
  • How to select a foreign key after narrowing down via…
  • Ukkonen's suffix tree algorithm in plain English
  • JSLint says "missing radix parameter"
  • Git status shows files as changed even though…
  • JavaScript keep the original array in recursive function
  • problem with client server unix domain stream…
  • Smart way to truncate long strings
  • Ordering dates in R with lubridate
  • PHP parse/syntax errors; and how to solve them
  • Am I paranoid? "Brutally" big Polymer website after…
  • Tips for Aggregating MongoDB Time Trend Data over…
  • How can I parse a CSV string with JavaScript, which…
  • Determine if a String is an Integer in Java
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Regular expression to match numbers with or without…
  • How to plot a wide dataframe with colors and…
  • Assigning a variable NaN in python without numpy
  • Numpy isnan() fails on an array of floats (from…
  • Simplest way to create Unix-like continuous pipeline…
  • The difference between the 'Local System' account…
  • Ember.js: Complex view layout, what's the proper approach?
  • How to download Xcode DMG or XIP file?
  • How do I convert a column from "unknown" to date in…
  • Getting the mode of a character column after every…
  • setTimeout function not working : javascript
  • TypeScript metadata reflection references other…
  • How to truncate float values?
  • For-each over an array in JavaScript
  • What is an IndexOutOfRangeException /…
  • Split a list from Dataframe column into specific column name
  • Detect whether a Python string is a number or a letter
  • How do I check if a type is a subtype OR the type of…
  • How does PHP 'foreach' actually work?
  • Docker compose fails to start a service with an…
  • Understanding PrimeFaces process/update and JSF…
  • Find the top 30% of the industry's revenue in the…
  • How to find Control in TemplateField of GridView?
  • how to use multiple ember data models in one view
  • How to parse an RSS feed using JavaScript?
  • How do I merge two dictionaries in a single…
  • Multiple dates rows to turn in 2 columns in a df…
  • Error: Cannot find module 'polka' on Heroku
  • What is the copy-and-swap idiom?
  • R replace multiple variables in a string using a…
  • VBA replace a string EXCEL 2019

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

not None test in Python

Next Post:

Why is “using namespace std;” considered bad practice?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error