0

I created a javascript method that checks if a number is a float. Each time I test the method for a float it keeps returning FALSE. I am not sure what I am doing wrong here. Any help would be really appreciated!

Below is my code.. Thanks!

function isFloat(n){

    var patt =  new RegExp('[+-]([0-9]*[.])?[0-9]+');
    return patt.test(n)
}


console.log(isFloat(12.40));
json2021
  • 2,146
  • 2
  • 14
  • 28

3 Answers3

3

There's a much easier way to check if a number is a float. Just compare the floored value against the original value. If they're the same, it's an integer.

function isFloat(n) {
  return Math.floor(n) !== n;
}

console.log(isFloat(1));
console.log(isFloat(1.2));
console.log(isFloat(12));
console.log(isFloat(12.4));

This will work if, and only if, you only use it on numbers. You can perform an additional check if you're worried about someone passing in non-numbers.

function isFloat(n) {
  return typeof n === 'number' && Math.floor(n) !== n;
}

Or you can simplify this even further by using Number.isInteger, provided you're running an environment that supports it.

function isFloat(n) {
  return typeof n === 'number' && !Number.isInteger(n);
}

console.log(isFloat(1));
console.log(isFloat(1.2));
console.log(isFloat(12));
console.log(isFloat(12.4));
console.log(isFloat('a'));
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

Your RegEx is wrong, it should be

/[+-]?\d+\.\d+/g

Also, as others noted, this is not the best solution for this. Use !Number.isInteger(num)

Bálint
  • 4,009
  • 2
  • 16
  • 27
0

The problem is that toString does not insert '+' before a number:

12.40.toString(); // "12.4", not "+12.4"

So you could use a regular expression like

new RegExp('[+-]?([0-9]*[.])?[0-9]+');

However, I recommend Validate decimal numbers in JavaScript - IsNumeric()

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513