Zerstoren
Zerstoren

Reputation: 126

Are there floating-point numbers in JavaScript?

I see many questions about methods to detect if a value is a floating-point number, but none of the examples work on numbers like as 1.0, 5.0, etc.

Is it possible to distinguish between numbers like 1 and 1.0 or 5 and 5.0? If yes, how can you detect a floating-point variable type?

Upvotes: 0

Views: 143

Answers (4)

Oliver Moran
Oliver Moran

Reputation: 5167

There is no such thing as a float or int basic types in JavaScript, only a number. So, there is no difference between 5.0 and 5.

If it is important to you (for whatever reason), you will need to store the value as a string then use parseFloat to extract the value.

For example:

var int = "5";
var float = "5.0";
console.log(int == float); // false
console.log(parseFloat(int) == parseFloat(float)); // true

How to print numbers to fixed number of decimal places

I've just spotted Zerstoren comment: "i get data from mongodb and want to print this data with strong typing."

The method toFixed can be used to print a number to fixed number of decimal places:

var num = 5;
console.log( num.toFixed(1) ); // 5.0

Upvotes: 0

Andrei B
Andrei B

Reputation: 2770

Zerstoren, the others are technically right: in javascript if you enter 2.0 or 2, there is no difference on how data is stored internally, so there is no way to find out if data was originally written as integer or float.

However, in case you want to validate some user form data, so that the user enters only integer numbers (e.g. order 2 pizzas, not 2.0) then the you do have a solution because that's actually a string (hence "2.0" is not same as "2"). You can use

typeof(n) =="string" && parseInt(n, 10) == n && n.indexOf('.')==-1

The first typeof condition is so that you fall under data is still in string format case I mentioned. See here: http://jsfiddle.net/X6U2d/

Andrei

Upvotes: 0

GameAlchemist
GameAlchemist

Reputation: 19294

I think the more concise answer is this one :

In javascript : 5 === 5.0.

So from this point on, no way can be found to distinguish them. They are strictly the same thing.

Edit : reminder : the only x such as (x!==x) in javascript is NaN.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234797

In Ecmascript 6, you can use isInteger:

var value = . . .;
Number.isInteger(value);

However, this is not widely supported yet. For now, you can use this:

function isInteger(value) {
    return typeof value === 'number' && (value | 0) === value;
}

This should work for all integer values that can be represented exactly in a 64-bit floating point representation.

Upvotes: 2

Related Questions