3

I'm using a function to to verify whether the number passed as a parameter is a float or an integer in JavaScript.
The method is working for numbers such as '4.34' i.e. with a non-zero decimal but it fails for numbers such as '3.0', returning integer instead of float.
This is the code I have been able to come up with so far

function dataType(x) {
    if (typeof x === 'number' && ){
        if (Math.round(x) === x ){
            return 'integer';
        }
        return 'float';
    }
}

console.log(dataType(8)); //integer
console.log(dataType(3.01)); //float
console.log(dataType(3.0)); // should return float

I would really appreciate some help on how to do this in JavaScript.
Thanks in advance.

Update: I want console.log(dataType(3.0)); to return float.

1

7 Answers 7

5

Every number in JS is a float. There is only one number type in JS (Number).

Thus, there's no cross-browser way of guaranteeing a difference between:

3
3.0
3.0000000000000

et cetera.

Even in a modern browser, (3.0000).toString( ) === "3"; //true.

Trying to cast or enforce numeric type safety in JS is rather pointless.
Work on the numbers in the Number format, convert into and out of string, using desired precision, as needed.

Sign up to request clarification or add additional context in comments.

Comments

2

I don't believe this is possible, unless you have access to a string representation of the value before it becomes a number. JavaScript throws away this information.

What problem are you trying to solve that warrants this differentiation?

1 Comment

This was a question asked in class. I just wanted to know if it is possible for this to be done.
1

A simple solution: Check if the remainder of dividing the number and its integer version is 0.

if(x % parseInt(x) == 0) 
     return 'integer';
 else return 'float';

1 Comment

or just if(x === parseInt(x)) :)
0

Try This

function dataType(x) {
    if (typeof x === 'number' ){
        if (Math.round(x) === x && x.toString().indexOf('.') < -1 ){
            return 'integer';
        }
        return 'float';
    }
}

2 Comments

Unfortunately this doesn't work because x.toString() will not preserve a .0
Gotcha! seems like something that isn't truly possible to do.
0

Maybe if you change the input, and compare what the change did?

Something along this line, (it can certainly be simplified somehow) ex:

function isFloat(x){ // example: x = 3.00 or x = 3.99

  if( typeof x === 'number' ){

      var obj = {};
      obj.ceil = false;
      obj.floor = false;
      obj.round = false;

      if( Math.ceil(x+0.1) === x ){
        obj.ceil = true;
      }
      if(Math.floor(x+0.1) === x ){
        obj.floor = true;
      }
      if (Math.round(x) === x ){
          obj.round = true;
      }

      if( obj.round == true){ // or use obj.floor?
        return "integer";
      }
      if( (obj.floor == true) && (obj.round == true) ) { // either && or || not sure
        return 'float';
      }
    }
}

By using for example these values 3.00 and 3.99 we get these "profiles" that can be used to identify the number (similar to a fingerprint):

(additional testing is needed with many more number types (I have only tested these 2 numbers with pen & paper), but I think this works)

isFloat(3.00){
  ceil  is false
  floor is true
  round is true
}

isFloat(3.99){
  ceil  is false
  floor is false
  round is false
}

Comments

0

I think I have found a much easier & WORKING solution:

Use the Number.prototype.toFixed() function.

That "locks" the number so JavaScript isn't allowed to round the number, to be smaller than the nr. of decimals you specify in the parentheses.

let int = 1
let float = 1.0;

console.log( "WARNING: toFixed() returns a: ", typeof float.toFixed(2) ); // string

console.log( "NOTICE: float is still a: ", typeof float ) // float

console.log( int === float , "<--- that is an incorrect result");
console.log( int.toString() === float.toFixed(1) ) // correct result here
console.log( int.toString() == float.toFixed(1) )
console.log( int.toString())
console.log( float.toFixed(1))

// You can "lock" the float variable like this:
float = float.toFixed(1);
// but now float is a: string
console.log( 'NOTICE: the "locked" float is now a: ', typeof float )
console.log( "and that will crash any future atempts to use toFixed() bacause that function does not exist on strings, only on numbers.");
console.log( "Expected crash here: " )
float.toFixed(1)

1 Comment

No! This does unfortunately not work, if: int=1.0 it will still report them as different, because toString() rounds it to 1 & toFixed() doesn't round it at all. And toFixed() also adds the "required" amount of trailing zeroes if a number is too short, which make the strings different from each other & therefore report it as false.
0

Every number in JS is a float. There is only one number type in JS (Number).

But if u want the def u can find it like this

function dataType(x) {
    if (typeof x === 'number' ){
        if (x.toString().indexOf('.') > -1 ){
            return 'integer';
        }
        return 'float';
    }
}

console.log(dataType(5.3)) // float
console.log(dataType(5)) // int

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.