Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>To check if a variable (including a string) is a number, check if it is not a number:</h2> <p>This works regardless of whether the variable contains is a string or number.</p> <pre><code>isNaN(num) // returns true if the variable does NOT contain a valid number </code></pre> <h3>Examples</h3> <pre><code>isNaN(123) // false isNaN('123') // false isNaN('1e10000') // false (This translates to Infinity, which is a number) isNaN('foo') // true isNaN('10px') // true </code></pre> <p>Of course, you can negate this if you need to. For example, to implement the <code>IsNumeric</code> example you gave:</p> <pre><code>function isNumeric(num){ return !isNaN(num) } </code></pre> <h2>To convert a string containing a number into a number:</h2> <p>only works if the string <em>only</em> contains numeric characters, else it returns <code>NaN</code>.</p> <pre><code>+num // returns the numeric value of the string, or NaN // if the string isn't purely numeric characters </code></pre> <h3>Examples</h3> <pre><code>+'12' // 12 +'12.' // 12 +'12..' // Nan +'.12' // 0.12 +'..12' // Nan +'foo' // NaN +'12px' // NaN </code></pre> <h2>To convert a string loosely to a number</h2> <p>useful for converting '12px' to 12, for example:</p> <pre><code>parseInt(num) // extracts a numeric value from the // start of the string, or NaN. </code></pre> <h3>Examples</h3> <pre><code>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. </code></pre> <h2>Floats</h2> <p>Bear in mind that, unlike <code>+num</code>, <code>parseInt</code> (as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use <code>parseInt()</code> <em>because of</em> this behaviour, <a href="https://jsperf.com/math-floor-vs-math-round-vs-parseint/33" rel="noreferrer">you're probably better off using another method instead</a>):</p> <pre><code>+'12.345' // 12.345 parseInt(12.345) // 12 parseInt('12.345') // 12 </code></pre> <h2>Empty strings</h2> <p>Empty strings may be a little counter-intuitive. <code>+num</code> converts empty strings to zero, and <code>isNaN()</code> assumes the same:</p> <pre><code>+'' // 0 isNaN('') // false </code></pre> <p>But <code>parseInt()</code> does not agree:</p> <pre><code>parseInt('') // NaN </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload