2

I am currently working on a project where I need to check if the user input a number value. The problem comes when he input a number starting with a decimal point (.20). I've been looking for a solution, but now I just give up. Neither isNaN or isNumeric works. Also tried to check like: if(value > 0), but this only works when the user input a leading zero. Any help would be greatly appreciated! Thanks in advance!

SOLVED: isNaN doesn't work for me because I use parseInt() instead of parseFloat(). Now everything works just fine. I want the administrators to excuse me for the dumb question I asked! This thread could now be deleted.

Emil Avramov
  • 881
  • 5
  • 21
  • 38

4 Answers4

0

Working Demohttp://jsfiddle.net/sPt7q/1

use

if(parseFloat(n) > 0){}

js in fiddle

var n = '.2';
if (n > 0) {
    alert(n);
}
if(parseFloat(n) > 0){
    alert(parseFloat(n));
}
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Try

function isInt(n) {
   return typeof n === 'number' && n % 1 == 0;
}

from: How do I check that a number is float or integer?

this does fail on 0.0 though.

Community
  • 1
  • 1
CBIII
  • 845
  • 1
  • 9
  • 9
0

A better and fool-proof way is to use regular expression:

var reg = new RegExp('^[1-9]\d*(\.\d+)?$');

or

var reg = new RegExp('^[1-9]\d*(\.\d+)?$');

The user input will be a string (from a form field). Check that string against this regex and that should work.

example:

 if(reg.test(userInput)) {
  //returns true
} else {
  //returns false
}
Rajesh
  • 3,743
  • 1
  • 24
  • 31
  • *Why* is it better than using `isNaN`? Do you have any facts to support your claim? Btw, your expression would not handle `'.2'` correctly. – Felix Kling Jul 20 '13 at 09:26
  • updated my regex. This will handle cases like 2, 0.2, .2 (without leadng zero), 2.222 etc. This regex checks for a number which can be a decimal also. – Rajesh Jul 20 '13 at 09:38
  • Still doesn't explain why it is "better". – Felix Kling Jul 20 '13 at 09:42
  • I would say better because it checks the exact pattern while eliminating use of parseInt(), isNaN and other number-manipulating functions. – Rajesh Jul 20 '13 at 09:47
0

Try this:

var val = .21;
if (!isNaN(val) && val.toString().indexOf('.') == -1) {
    console.log('valid number:' + val);
} else {
    console.log('invalid number: ' + val);
}

jsFiddle

Manoj Yadav
  • 6,560
  • 1
  • 23
  • 21