PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

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

 August 10, 2022     decimal, floating-point, integer, javascript, types     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing