Wednesday, August 10, 2022

[FIXED] How to differentiate between a one-decimal float and integer in JavaScript

Issue

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.


Solution

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.



Answered By - Norguard
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.