What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

- Clarity. Solution should be clean and simple.
- Cross-platform.

Test cases:

```
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef')=> false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
```

This way seems to work well:

```
function IsNumeric(input){
var RE = /^-{0,1}\d*\.{0,1}\d+$/;
return (RE.test(input));
}
```

And to test it:

```
// alert(TestIsNumeric());
function TestIsNumeric(){
var results = ''
results += (IsNumeric('-1')?"Pass":"Fail") + ": IsNumeric('-1') => true\n";
results += (IsNumeric('-1.5')?"Pass":"Fail") + ": IsNumeric('-1.5') => true\n";
results += (IsNumeric('0')?"Pass":"Fail") + ": IsNumeric('0') => true\n";
results += (IsNumeric('0.42')?"Pass":"Fail") + ": IsNumeric('0.42') => true\n";
results += (IsNumeric('.42')?"Pass":"Fail") + ": IsNumeric('.42') => true\n";
results += (!IsNumeric('99,999')?"Pass":"Fail") + ": IsNumeric('99,999') => false\n";
results += (!IsNumeric('0x89f')?"Pass":"Fail") + ": IsNumeric('0x89f') => false\n";
results += (!IsNumeric('#abcdef')?"Pass":"Fail") + ": IsNumeric('#abcdef') => false\n";
results += (!IsNumeric('1.2.3')?"Pass":"Fail") + ": IsNumeric('1.2.3') => false\n";
results += (!IsNumeric('')?"Pass":"Fail") + ": IsNumeric('') => false\n";
results += (!IsNumeric('blah')?"Pass":"Fail") + ": IsNumeric('blah') => false\n";
return results;
}
```

I borrowed that regex from http://www.codetoad.com/javascript/isnumeric.asp. Explanation:

```
/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string
```

A couple of tests to add:

```
IsNumeric('01.05') => false
IsNumeric('1.') => false
IsNumeric('.') => false
```

I came up with this:

```
function IsNumeric(input) {
return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(input);
}
```

The solution covers:

- An optional negative sign at the beginning
- A single zero, or one or more digits not starting with 0, or nothing so long as a period follows
- A period that is followed by 1 or more numbers

I'd like to add the following:

```
1. IsNumeric('0x89f') => true
2. IsNumeric('075') => true
```

Positive hex numbers start with 0x and negative hex numbers start with -0x. Positive oct numbers start with 0 and negative oct numbers start with -0. This one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (4e3.2 is not valid).

```
function IsNumeric(input){
var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
return (RE.test(input));
}
```

Use the function isNaN. I believe if you test for `!isNaN(yourstringhere)`

it works fine for any of these situations.

Yeah, the built-in `isNaN(object)`

will be much faster than any regex parsing, because it's built-in and compiled, instead of interpreted on the fly.

Although the results are somewhat different to what you're looking for (try it):

```
// IS NUMERIC
document.write(!isNaN('-1') + "<br />"); // true
document.write(!isNaN('-1.5') + "<br />"); // true
document.write(!isNaN('0') + "<br />"); // true
document.write(!isNaN('0.42') + "<br />"); // true
document.write(!isNaN('.42') + "<br />"); // true
document.write(!isNaN('99,999') + "<br />"); // false
document.write(!isNaN('0x89f') + "<br />"); // true
document.write(!isNaN('#abcdef') + "<br />"); // false
document.write(!isNaN('1.2.3') + "<br />"); // false
document.write(!isNaN('') + "<br />"); // true
document.write(!isNaN('blah') + "<br />"); // false
```

It can be done without RegExp as

```
function IsNumeric(data){
return parseFloat(data)==data;
}
```

Arrrgh! Don't listen to the regular expression answers. RegEx is icky for this, and I'm not talking just performance. It's so easy to make subtle, impossible to spot mistakes with your regular expression.

If you can't use `isNaN()`

, this should work much better:

```
function IsNumeric(input)
{
return (input - 0) == input && (''+input).replace(/^\s+|\s+$/g, "").length > 0;
}
```

Here's how it works:

The `(input - 0)`

expression forces JavaScript to do type coercion on your input value; it must first be interpreted as a number for the subtraction operation. If that conversion to a number fails, the expression will result in `NaN`

. This *numeric* result is then compared to the original value you passed in. Since the left hand side is now numeric, type coercion is again used. Now that the input from both sides was coerced to the same type from the same original value, you would think they should always be the same (always true). However, there's a special rule that says `NaN`

is never equal to `NaN`

, and so a value that can't be converted to a number (and only values that cannot be converted to numbers) will result in false.

The check on the length is for a special case involving empty strings. Also note that it falls down on your 0x89f test, but that's because in many environments that's an okay way to define a number literal. If you want to catch that specific scenario you could add an additional check. Even better, if that's your reason for not using `isNaN()`

then just wrap your own function around `isNaN()`

that can also do the additional check.

In summary, *if you want to know if a value can be converted to a number, actually try to convert it to a number.*

I went back and did some research for *why* a whitespace string did not have the expected output, and I think I get it now: an empty string is coerced to `0`

rather than `NaN`

. Simply trimming the string before the length check will handle this case. Note that I opted for a regex-based trim rather than the .trim() function in order to support IE8 (and yes, I'm aware of the irony in starting my answer by dissing regex and then using one in the code, even if only in a limited way). About this time next year when Windows XP is no longer supported I'll come back and update it to use the .trim() function (and remove these two sentences... if I remember).

Running the unit tests against the new code and it only fails on the infinity and boolean literals, and the only time that should be a problem is if you're generating code (really, who would type in a literal and check if it's numeric? You should *know*), and that would be some strange code to generate.

But, again, **the only reason ever to use this is if for some reason you have to avoid isNaN().**

Yahoo! UI uses this:

```
isNumber: function(o) {
return typeof o === 'number' && isFinite(o);
}
```

```
function IsNumeric(num) {
return (num >=0 || num < 0);
}
```

This works for 0x23 type numbers as well.

@Joel's answer is pretty close, but it will fail in the following cases:

```
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
```

Some time ago I had to implement an `IsNumeric`

function, to find out if a variable contained a numeric value, **regardless its type**, it could be a `String`

containing a numeric value (I had to consider also exponential notation, etc.), a `Number`

object, virtually anything could be passed to that function, I couldn't make any type assumption, taking care of type coercion (eg. `+true == 1;`

but `true`

shouldn't be considered as `"numeric"`

).

I think is worth sharing this set of **+30 unit tests** made to numerous function implementations, and also share the one that passes all my tests:

```
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
```

**Update** : Here's how jQuery does it now (Mid-2014) :

```
isNumeric: function( obj ) {
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
}
```

**P.S.** isNaN & isFinite have a confusing behavior due to forced conversion to number. In ES6, Number.isNaN & Number.isFinite would fix these issues. Keep that in mind when using them.

To me, this is the best way:

```
isNumber : function(v){
return typeof v === 'number' && isFinite(v);
}
```

This should work. Some of the functions provided here are flawed, also should be faster than any other function here.

```
function isNumeric(n)
{
var n2 = n;
n = parseFloat(n);
return (n!='NaN' && n2==n);
}
```

Explained:

Create a copy of itself, then converts the number into float, then compares itself with the original number, if it is still a number, (whether integer or float) , and matches the original number, that means, it is indeed a number.

It works with numeric strings as well as plain numbers. Does not work with hexadecimal numbers.

Warning: use at your own risk, no guarantees.

The following may work as well.

```
function isNumeric(v) {
return v.length > 0 && !isNaN(v) && v.search(/[A-Z]|[#]/ig) == -1;
};
```

```
return (input - 0) == input && input.length > 0;
```

didn't work for me. When I put in an alert and tested, `input.length`

was 'undefined'. I think there is no property to check integer length. So what I did was

```
var temp = '' + input;
return (input - 0) == input && temp.length > 0;
```

It worked fine.

My solution,

```
function isNumeric(input) {
var number = /^\-{0,1}(?:[0-9]+){0,1}(?:\.[0-9]+){0,1}$/i;
var regex = RegExp(number);
return regex.test(input) && input.length>0;
}
```

It appears to work in every situation, but I might be wrong.

An integer value can be verified by:

```
function isNumeric(value) {
var bool = isNaN(+value));
bool = bool || (value.indexOf('.') != -1);
bool = bool || (value.indexOf(",") != -1);
return !bool;
};
```

This way is easier and faster! All tests are checked!

@Zoltan Lengyel 'other locales' comment (Apr 26 at 2:14) in @CMS Dec answer (2 '09 at 5:36):

I would recommend testing for typeof (n) === 'string':

```
function isNumber(n) {
if (typeof (n) === 'string') {
n = n.replace(/,/, ".");
}
return !isNaN(parseFloat(n)) && isFinite(n);
}
```

This extends Zoltans recommendation to not only be able to test "localized numbers" like isNumber('12,50') but also "pure" numbers like isNumber(2011).

Well, I'm using this one I made...

It's been working so far:

```
function checkNumber(value) {
if ( value % 1 == 0 )
return true;
else
return false;
}
```

If you spot any problem with it, tell me, please.

Like any numbers should be divisible by one with nothing left, I figured I could just use the module, and if you try dividing a string into a number the result wouldn't be that. So.

If I'm not mistaken, this should match any valid JavaScript number value, excluding constants (Infinity, NaN) and the sign operators `+/-`

(because they are not actually part of the number as far as I concerned, they are separate operators):

I needed this for a tokenizer, where sending the number to JavaScript for evaluation wasn't an option... It's definitely not the shortest possible regular expression, but I believe it catches all the finer subtleties of JavaScript's number syntax.

```
/^(?:(?:(?:[1-9]\d*|\d)\.\d*|(?:[1-9]\d*|\d)?\.\d+|(?:[1-9]\d*|\d))(?:[e]\d+)?|0[0-7]+|0x[0-9a-f]+)$/i
```

Valid numbers would include:

- 0
- 00
- 01
- 10
- 0e1
- 0e01
- .0
- 0.
- .0e1
- 0.e1
- 0.e00
- 0xf
- 0Xf

Invalid numbers would be

- 00e1
- 01e1
- 00.0
- 00x0
- .
- .e0

I'm using simpler solution:

```
function isNumber(num) {
return parseFloat(num).toString() == num
}
```

The simplest way for validate decimal numbers in JavaScript is:

```
function isDecimal(n){
if( (n!='') && ((n-n) == 0) ){
return true;
}
else{
return false;
}
}
```

When we call this function, it returns true for decimal numbers.

Here I've collected the "good ones" from this page and put them into a simple test pattern for you to evaluate on your own.

For newbies, the "console.log" is a built in function (available in all normal browsers) that lets you output results to the JavaScript console (dig around, you'll find it) rather than having to output to your HTML page.

```
var isNumeric = function(val){
// --------------------------
// Recommended
// --------------------------
// jQuery - works rather well
// See CMS's unit test also: http://dl.getdropbox.com/u/35146/js/tests/isNumber.html
return !isNaN(parseFloat(val)) && isFinite(val);
// Aquatic - good and fast, fails the "0x89f" test, but that test is questionable.
//return parseFloat(val)==val;
// --------------------------
// Other quirky options
// --------------------------
// Fails on "", null, newline, tab negative.
//return !isNaN(val);
// user532188 - fails on "0x89f"
//var n2 = val;
//val = parseFloat(val);
//return (val!='NaN' && n2==val);
// Rafael - fails on negative + decimal numbers, may be good for isInt()?
// return ( val % 1 == 0 ) ? true : false;
// pottedmeat - good, but fails on stringy numbers, which may be a good thing for some folks?
//return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(val);
// Haren - passes all
// borrowed from http://www.codetoad.com/javascript/isnumeric.asp
//var RE = /^-{0,1}\d*\.{0,1}\d+$/;
//return RE.test(val);
// YUI - good for strict adherance to number type. Doesn't let stringy numbers through.
//return typeof val === 'number' && isFinite(val);
// user189277 - fails on "" and "\n"
//return ( val >=0 || val < 0);
}
var tests = [0, 1, "0", 0x0, 0x000, "0000", "0x89f", 8e5, 0x23, -0, 0.0, "1.0", 1.0, -1.5, 0.42, '075', "01", '-01', "0.", ".0", "a", "a2", true, false, "#000", '1.2.3', '#abcdef', '', "", "\n", "\t", '-', null, undefined];
for (var i=0; i<tests.length; i++){
console.log( "test " + i + ": " + tests[i] + " \t " + isNumeric(tests[i]) );
}
```

Since jQuery 1.7, you can use `jQuery.isNumeric()`

:

```
$.isNumeric('-1'); // true
$.isNumeric('-1.5'); // true
$.isNumeric('0'); // true
$.isNumeric('0.42'); // true
$.isNumeric('.42'); // true
$.isNumeric('0x89f'); // true (valid hexa number)
$.isNumeric('99,999'); // false
$.isNumeric('#abcdef'); // false
$.isNumeric('1.2.3'); // false
$.isNumeric(''); // false
$.isNumeric('blah'); // false
```

Just note that unlike what you said, `0x89f`

is a valid number (hexa)

The accepted answer failed your test #7 and I guess it's because you changed your mind. So this is a response to the accepted answer, with which I had issues.

During some projects I have needed to validate some data and be as certain as possible that it is a javascript numerical value that can be used in mathematical operations.

jQuery, and some other javascript libraries already include such a function, usually called isNumeric. There is also a post on stackoverflow that has been widely accepted as the answer, the same general routine that the afore mentioned libraries are using.

```
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
```

First, the code above would return true if the argument was an array of length 1, and that single element was of a type deemed as numeric by the above logic. In my opinion, if it's an array then its not numeric.

To alleviate this problem, I added a check to discount arrays from the logic

```
function isNumber(n) {
return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n);
}
```

Of course, you could also use `Array.isArray`

, jquery `$.isArray`

or prototype `Object.isArray`

instead of `Object.prototype.toString.call(n) !== '[object Array]'`

My second issue was that Negative Hexadecimal integer literal strings ("-0xA" -> -10) were not being counted as numeric. However, Positive Hexadecimal integer literal strings ("0xA" -> 10) were treated as numeric. I needed both to be valid numeric.

I then modified the logic to take this into account.

```
function isNumber(n) {
return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));
}
```

If you are worried about the creation of the regex each time the function is called then you could rewrite it within a closure, something like this

```
var isNumber = (function () {
var rx = /^-/;
return function (n) {
return Object.prototype.toString.call(n) !== '[object Array]' &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(rx, ''));
};
}());
```

I then took CMSs +30 test cases and cloned the testing on jsfiddle added my extra test cases and my above described solution.

It may not replace the widely accepted/used answer but if this is more of what you are expecting as results from your isNumeric function then hopefully this will be of some help.

**EDIT:** As pointed out by Bergi, there are other possible objects that could be considered numeric and it would be better to whitelist than blacklist. With this in mind I would add to the criteria.

I want my isNumeric function to consider only Numbers or Strings

With this in mind, it would be better to use

```
function isNumber(n) {
return (Object.prototype.toString.call(n) === '[object Number]' || Object.prototype.toString.call(n) === '[object String]') &&!isNaN(parseFloat(n)) && isFinite(n.toString().replace(/^-/, ''));
}
```

**knockoutJs Inbuild library validation functions**

By extending it the field get validated

1.) number

self.number = ko.observable(numberValue)**.extend({ number: true})**;

TestCase

```
numberValue = '0.0' --> true
numberValue = '0' --> true
numberValue = '25' --> true
numberValue = '-1' --> true
numberValue = '-3.5' --> true
numberValue = '11.112' --> true
numberValue = '0x89f' --> false
numberValue = '' --> false
numberValue = 'sfsd' --> false
numberValue = 'dg##$' --> false
```

2.)digit

self.number = ko.observable(numberValue)**.extend({ digit: true})**;

TestCase

```
numberValue = '0' --> true
numberValue = '25' --> true
numberValue = '0.0' --> false
numberValue = '-1' --> false
numberValue = '-3.5' --> false
numberValue = '11.112' --> false
numberValue = '0x89f' --> false
numberValue = '' --> false
numberValue = 'sfsd' --> false
numberValue = 'dg##$' --> false
```

2.)min and max

self.number = ko.observable(numberValue)**.extend({ min: 5}).extend({ max: 10})**;

This field accept value between 5 and 10 only

TestCase

```
numberValue = '5' --> true
numberValue = '6' --> true
numberValue = '6.5' --> true
numberValue = '9' --> true
numberValue = '11' --> false
numberValue = '0' --> false
numberValue = '' --> false
```

@CMS' answer: Your snippet failed on whitespace cases on my machine using nodejs. So I combined it with @joel's answer to the following:

```
is_float = function(v) {
return !isNaN(v) && isFinite(v) &&
(typeof(v) == 'number' || v.replace(/^\s+|\s+$/g, '').length > 0);
}
```

I unittested it with those cases that are floats:

```
var t = [
0,
1.2123,
'0',
'2123.4',
-1,
'-1',
-123.423,
'-123.432',
07,
0xad,
'07',
'0xad'
];
```

and those cases that are no floats (including empty whitespaces and objects / arrays):

```
var t = [
'hallo',
[],
{},
'jklsd0',
'',
"\t",
"\n",
' '
];
```

Everything works as expected here. Maybe this helps.

Full source code for this can be found here.

Here's a lil bit improved version (probably the fastest way out there) that I use instead of exact jQuery's variant, I really don't know why don't they use this one:

```
function isNumeric(val) {
return !isNaN(+val) && isFinite(val);
}
```

The downside of jQuery's version is that if you pass a string with leading numerics and trailing letters like `"123abc"`

the `parseFloat | parseInt`

will extract the numeric fraction out and return 123, BUT, the second guard `isFinite`

will fail it anyway. With the unary `+`

operator it will die on the very first guard since + throws NaN for such hybrids :) A little performance yet I think a solid semantic gain.

Only problem I had with @CMS's answer is the exclusion of NaN and Infinity, which are useful numbers for many situations. One way to check for NaN's is to check for numeric values that don't equal themselves, `NaN != NaN`

! So there are really 3 tests you'd like to deal with ...

```
function isNumber(n) {
n = parseFloat(n);
return !isNaN(n) || n != n;
}
function isFiniteNumber(n) {
n = parseFloat(n);
return !isNaN(n) && isFinite(n);
}
function isComparableNumber(n) {
n = parseFloat(n);
return (n >=0 || n < 0);
}
isFiniteNumber('NaN')
false
isFiniteNumber('OxFF')
true
isNumber('NaN')
true
isNumber(1/0-1/0)
true
isComparableNumber('NaN')
false
isComparableNumber('Infinity')
true
```

My isComparableNumber is pretty close to another elegant answer, but handles hex and other string representations of numbers.

I found simple solution, probably not best but it's working fine :)

So, what I do is next, I parse string to Int and check if length size of new variable which is now int type is same as length of original string variable. Logically if size is the same it means string is fully parsed to int and that is only possible if string is "made" only of numbers.

```
var val=1+$(e).val()+'';
var n=parseInt(val)+'';
if(val.length == n.length )alert('Is int');
```

You can easily put that code in function and instead of alert use return true if int. Remember, if you use dot or comma in string you are checking it's still false cos you are parsing to int.

Note: Adding 1+ on e.val so starting zero wouldn't be removed.

I have run the following below and it passes all the test cases...

It makes use of the different way in which parseFloat and Number handle their inputs...

```
function IsNumeric(_in) {
if (parseFloat(_in) === Number(_in) && Number(_in) !== NaN)
return true;
return false;
}
```

The following seems to works fine for many cases:

```
function isNumeric(num) {
return (num > 0 || num === 0 || num === '0' || num < 0) && num !== true && isFinite(num);
}
```

This is built on top of this answer (which is for this answer too): http://stackoverflow.com/a/1561597/1985601

I realize the original question did not mention jQuery, but if you do use jQuery, you can do:

```
$.isNumeric(val)
```

Simple.

https://api.jquery.com/jQuery.isNumeric/ (as of jQuery 1.7)

I realize this has been answered many times, but the following is a decent candidate which can be useful in some scenarios.

it should be noted that it assumes that '.42' is NOT a number, and '4.' is NOT a number, so this should be taken into account.

```
function isDecimal(x) {
return return '' + x === '' + +x;
}
function isInteger(x) {
return return '' + x === '' + parseInt(x);
}
```

The `isDecimal`

passes the following test:

```
function testIsNumber(f) {
return f('-1') && f('-1.5') && f('0') && f('0.42')
&& !f('.42') && !f('99,999') && !f('0x89f')
&& !f('#abcdef') && !f('1.2.3') && !f('') && !f('blah');
}
```

The idea here is that every number or integer has one "canonical" string representation, and every non-canonical representation should be rejected. So we cast to a number and back, and see if the result is the original string.

Whether these functions are useful for you depends on the use case. One feature is that *distinct strings represent distinct numbers* (if both pass the `isNumber()`

test).

This is relevant e.g. for numbers as object property names.

```
var obj = {};
obj['4'] = 'canonical 4';
obj['04'] = 'alias of 4';
obj[4]; // prints 'canonical 4' to the console.
```

I use this way to chack that varible is numeric:

```
v * 1 == v
```

```
function isNumber(n) {
return (n===n+''||n===n-0) && n*0==0 && /\S/.test(n);
}
```

Explanations:

(n===n-0||n===n+'') verifies if n is a number or a string (discards arrays, boolean, date, null, ...). You can replace (n===n-0||n===n+'') by n!==undefined && n!==null && (n.constructor===Number||n.constructor===String): significantly faster but less concise.

n*0==0 verifies if n is a finite number as isFinite(n) does. If you need to check strings that represent negative hexadecimal, just replace n*0==0 by something like n.toString().replace(/^\s*-/,'')*0==0. It costs a little of course, so if you don't need it, don't use it.

/\S/.test(n) discards empty strings or strings that contain only white-spaces (necessary since isFinite(n) or n*0==0 return a false positive in this case). You can reduce the number of call to .test(n) by using (n!=0||/0/.test(n)) instead of /\S/.test(n), or you can use a slightly faster but less concise test such as (n!=0||(n+'').indexOf('0')>=0): tiny improvement.

Slightly improved answer:

```
function isNumber(num) {
return parseFloat(num) === parseFloat(num) && isFinite(num);
}
```

Above code is independent of isNaN function and uses best way to check NaN. If value is not equal to itself then that is NaN.

None of the answers return false for empty strings, a fix for that...

```
function is_numeric(n)
{
var r = false;
if (n!='' && !isNaN(parseFloat(n)) && isFinite(n)) {r = true;}
return r;
}
```

One can use a type-check library like https://github.com/arasatasaygin/is.js or just extract a check snippet from there (https://github.com/arasatasaygin/is.js/blob/master/is.js#L131):

```
is.nan = function(value) { // NaN is number :)
return value !== value;
};
// is a given value number?
is.number = function(value) {
return !is.nan(value) && Object.prototype.toString.call(value) === '[object Number]';
};
```

In general if you need it to validate parameter types (on entry point of function call), you can go with JSDOC-compliant contracts (https://www.npmjs.com/package/bycontract):

```
/**
* This is JSDOC syntax
* @param {number|string} sum
* @param {Object.<string, string>} payload
* @param {function} cb
*/
function foo( sum, payload, cb ) {
// Test if the contract is respected at entry point
byContract( arguments, [ "number|string", "Object.<string, string>", "function" ] );
}
// Test it
foo( 100, { foo: "foo" }, function(){}); // ok
foo( 100, { foo: 100 }, function(){}); // exception
```

If you need to validate a special set of decimals y you can use this simple javascript:

http://codesheet.org/codesheet/x1kI7hAD

```
<input type="text" name="date" value="" pattern="[0-9]){1,2}(\.){1}([0-9]){2}" maxlength="6" placeholder="od npr.: 16.06" onchange="date(this);" />
```

The Javascript:

```
function date(inputField) {
var isValid = /^([0-9]){1,2}(\.){1}([0-9]){2}$/.test(inputField.value);
if (isValid) {
inputField.style.backgroundColor = '#bfa';
} else {
inputField.style.backgroundColor = '#fba';
}
return isValid;
}
```

`isNumeric=(el)=>{return Boolean(parseFloat(el)) && isFinite(el)}`

Nothing very different but we can use Boolean constructor

To check if a variable contains a valid number and not just a String which looks like a number, `Number.isFinite(value)`

can be used.

This is part of the language since ES2015

Examples:

```
Number.isFinite(Infinity) // false
Number.isFinite(NaN) // false
Number.isFinite(-Infinity) // false
Number.isFinite(0) // true
Number.isFinite(2e64) // true
Number.isFinite('0') // false
Number.isFinite(null) // false
```

```
function isNumeric(n) {
var isNumber = true;
$.each(n.replace(/ /g,'').toString(), function(i, v){
if(v!=',' && v!='.' && v!='-'){
if(isNaN(v)){
isNumber = false;
return false;
}
}
});
return isNumber;
}
```

isNumeric(-3,4567.89); // true

isNumeric(3,4567.89); // true

isNumeric("-3,4567.89"); // true

isNumeric(3d,4567.89); // false

Best way to do this is like this:

```
function isThisActuallyANumber(data){
return ( typeof data === "number" && !isNaN(data) );
}
```

I think parseFloat function can do all the work here. The function below passes all the tests on this page including isNumeric(Infinity) == true:

```
function isNumeric(n)
{
return parseFloat(n) == n;
}
```

```
function inNumeric(n){
return Number(n)+'' === n;
}
```

I think my code is perfect ...

```
/**
* @param {string} s
* @return {boolean}
*/
var isNumber = function(s) {
return s.trim()!=="" && !isNaN(Number(s));
};
```

```
$('.rsval').bind('keypress', function(e){
var asciiCodeOfNumbers = [48,46, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57];
var keynum = (!window.event) ? e.which : e.keyCode;
var splitn = this.value.split(".");
var decimal = splitn.length;
var precision = splitn[1];
if(decimal == 2 && precision.length >= 2 ) { console.log(precision , 'e'); e.preventDefault(); }
if( keynum == 46 ){
if(decimal > 2) { e.preventDefault(); }
}
if ($.inArray(keynum, asciiCodeOfNumbers) == -1)
e.preventDefault();
});
```

Similar Questions

As the title suggests I need a regular expression that can validate an input string to make sure it is a number between 1-30 and up to 2 decimal places. For instance, 4 is fine 10.25 is fine 15.3 is

I want to validate numbers and I only know the decimal separator ( dot or comma ) Eg.1: n1=12.4 and n2=1,234.5 -> both are valid for '.' as decimal separator and both invalid for ',' as decimal sep

Does anyone know a regular expression to validate MSISDN-format mobile numbers? I looked into a solution posted at http://charlvn.blogspot.com/2010/06/msisdn-regular-expressions.html but I think that'

I have a decimal field that I receive back in a controller in C# MVC. I need to know if it's value in decimal has no more than three positions. So 0.00 is accepted as well as 0.01, but 0.001 would be

I Have this code to find out the total purchase price of some numbers and i need to know how to round the numbers to only 2 decimal places. #include <iostream.h> #include <cstdlib.h> #incl

This question already has an answer here: Python rounding error with float numbers 2 answers Python weird addition bug [duplicate] 4 answers I'm trying to add decimal numbers a decimal numb

Below is the function to validate date. The should be between Today - 15 and Today. Can some one refactor this code. phpdatetoday is a string in the form 2010,Dec,3 function validate(page, phpdatetoda

I am trying to build a regex which will allow both negative and positive decimal numbers with the following rules. there can not be more than 2 digits after decimal point Decimal point is optional To

I have a problem with decimal numbers. If I use .(dot) instead of ,(comma) in the textbox it comes null in controller. I know its a language issue because in spanish we use comma instead of dot for de

I have this in my view model: [Required(ErrorMessage = Price is required)] [Range(0.01, 999999999, ErrorMessage = Price must be greater than 0.00)] [DisplayName(Price ($))] public decimal Price

This question already has an answer here: how to validate credit card number 8 answers I am trying to validate a credit card number by a javascript function. I am taking an input by html form a

Can anyone suggest me a way to multiply decimal numbers without using multiplication(*) sign. I know it looks like homework thing, but I just want to know how to achieve this. I have already done this

I'm working with visual studio 2008 developing software for windows CE 6.0, compact framework. I'm having this strange? trouble with isNumeric method. Is there another better way to do this job? Why

How to prevent or validate the user entering numbers 6 digits with range (eg: 100000) and two decimal digits in a textbox using javascript ? I m using onkeypress event in my textbox my code is: var t

Here is the following code, I am learning Javascript on my own and wanted to know how I could validate my code to make the textboxes say something like please enter a value or please enter a valid

I am working currently with PHP validation of decimal values. The function works well in determining decimals/integers from letters but my goal is to format the decimal/integer values into proper curr

I am trying to print the numbers simply in the sequence i.e 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 using Loop, First i converted each number into Hexa printed it reset it to the decimal in

I am trying to get my divisibility checker code to work correctly. It currently only works with whole positive numbers. If the number is a decimal or a negative number the code will not work. I know I

My program should convert decimal numbers to binary. For big numbers it is giving me a negative number not a binary number. Why is this? For example, if I supply 2321 I get 100100010001, which is fine

Possible Duplicate: JavaScript: formatting number with exactly two decimals I need a JS (jQuery) script, that helps me limit the input of numbers to two decimal points. I have tried this and it work

I have this question about decimal numbers from oracle to php. If i have 0,7 on oracle, for example, when i use it on php, it will be ,7, without the zero. Anyone one knows why? And a possible sol

What would be the javascript regex to determine whether the digits after the decimal point are only zero and the number of zeros after the decimal point is greater than two? Some test cases: 8 ->

I'm trying to write a regex for javascript which will allow letters and numbers but won't allow numbers alone. So '12 Test Street' would validate, as would 'test street' but not '12'. Not that familia

I have the following string and want to remove all double quotes in front of and at the end of decimal numbers keeping other quotes. {id:default,values:{level1:[0.0000,0.0000,0.0000],l

As the title of the question, I need to validate regex using the following values: (Maximum 2 decimal places, and 9 integers) with an optional percent symbol. Valid: 10% 0% 1111111.12% 15.2% 10 2.3

I have the below JavaScript syntax: var discount = Math.round(100 - (price / listprice) * 100); This rounds up to the whole number, how can I return the result with two decimal places?

How to restrict the number of digits after the decimal point using onkeyup even in javascript? I want to restrict the number of digits after the decimal point based on an input already given in the

I need to compare the following scenarios using decimal comparison in jquery. var a=99999999999.99; var b=9999999999999999999 if(parseFloat(a).toFixed(2) > parseFloat(b).toFixed(2)) This always re

i want to validate decimal no like 0.5,0.05 and also natural no. For natural no i used this pattern /^[0-9]{1,7}$/. what pattern i will use for decimal no and natural no together?

I am using <input type=number> where I place values using Javascript. I'd like to format these numbers to have always one decimal. Chrome stubbornly strips out of trailing zero from the numbers

I'm using a simple loop to echo back some numbers <?php $inc = 0.25; $start = 0.25; $stop = 5.00; ?> <?php while($start != ($stop + $inc)){ ?> <option><?php echo $start ?></

I am trying to write recursive function which converts a binary numbers into decimal system. I couldn't find the bug. Any help will be appreciated deeply. Here is my first attempt: #include <iostre

Possible Duplicate: Elegant workaround for JavaScript floating point number problem Why is it that when adding 2 numbers together using javascript, it will return a crazy number of decimal points? I

Is there any difference between $.isNumeric and !isNaN()? I don't see where they will ever return different results.

How do I generate cryptographically secure random numbers in javascript?

I want to avoid from decimal numbers in my Axis, how can I do that ? XAML: <Charting:Chart VerticalAlignment=Stretch HorizontalContentAlignment=Stretch> <Charting:Chart.Axes> <Cha

Using JSONObject to read a json response from a server. The server returns some decimal number. Normal numbers are not a problem to but the problem occurs when there is decimal number of form 0.00068.

I have a series of CSV files where numbers are formatted in the european style using commas instead of decimal points, i.e. 0,5 instead of 0.5. There are too many of these files to edit them before im

Could anyone tell me what RegEx would work to validate an international phone number including white space between the numbers and also allowing for these chars: - ( ). The amount of numbers in the st

Is there a fast way to convert numbers with exponential notation (examples: 0.5e10 or -5e20) to decimal or double? Update: I found C# Parse a Number from Exponential Notation but the examples won'

Recently I run into the well known floating point precision errors of Javascript. Usually I would avoid floating point calculations on the thin client & rather leave it to the back-end. I started

I have some inputs on my site representing floating point numbers with up to ten precision digits (in decimal). At some point, in the client side validation code, I need to compare a couple of those v

I have to validate using regex decimal number between 00.00 to 35.35 with following simple assumptions(I am using C#). 1) leading zeros are not required(optional). 2) 2 decimals are always required. I

I'm going to put all decimal numbers in a text inside a span tag (<span>) but the numbers are not using period as decimal separator, they use slash (/) The sample text is something like this: Th

I have been trying to write a Lex program to convert octal numbers to decimal numbers. But after accepting the number as input, but not doing anything. No output. And no program termination. The progr

How do I validate phone numbers using JavaScript in ASP.NET?

im trying to create a form that takes 3 values, a name, a weight and height. i want to force the user to only enter numbers and not letters, so using the isNumeric this works but only for WEIGHT, not

I have a text input field in which I want to insert just numbers, then a comma, and then just two decimal digits. I'm trying to obtain this via jQuery, using Masked Input Plugin, but it seems not to w

My knowledge of regex is very weak. So far I have manage to create an expression that verifies if a string is an integer or not. The issues is that I only want decimal numbers NO WHOLE numbers at all.

I have a basic doubt in how to proceed in my application. I have a form and I need to validate that all the inputs which are numbers. I have a problem in deciding the type of the attributes of the bea