KingNestor
KingNestor

Reputation: 67960

How should I convert a number to either float or integer, if I don't know which one it is?

I'm working on a program that reads in users input as a string, which includes reading in some numbers and operators.

I'm now trying to determine how to parse a string which I know to be a number but I don't know if it is a float or an integer.

I have a few ideas:

function parseNumber(number)
{
    if (number % 1 == 0)
        return parseInt(number);
    else 
        return parseFloat(number);
}

or

function parseNumber(number)
{
    if (number.indexOf(".") != -1)
        return parseFloat(number);
    else
        return parseInt(number);
}

or

function parseNumber(number)
{
    if (!number.matches(/([0-9]+.[0-9]+)/))
        return parseInt(number);
    else
        return parseFloat(number);
}

And I can think of a few other ways.

Which way seems to be the best?

Upvotes: 0

Views: 280

Answers (5)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

JavaScript has a only one numeric type, Number. Internally, it is represented as 64-bit floating point.

Unlike most other programming languages, there is no separate integer type, so 5 and 5.0 are the same value.

To convert a string to Number most of the times I simply use the unary plus operator:

var numberString = "10";
var numberValue = +numberString;

Upvotes: 1

Lucero
Lucero

Reputation: 60190

Why would you need to make a difference between ints and doubles for the shunting-yard algorithm? Both are numbers, and to my understanding that's all which counts. Just use parseFloat() after you've determined that your token is numeric.

Upvotes: 1

Matt Briggs
Matt Briggs

Reputation: 42178

At least on webkit (what I have open right now), parseFloat and parseInt both return numbers, the only difference is that parseInt will chop off anything passed the ".".

To get the type of an object in javascript, try something like this

a = parseFloat("55.5")
a.constructor.toString() // returns Number
b = parseFloat("55")
b.constructor.toString() // returns Number
c = parseInt("55")
c.constructor.toString() // returns Number

Upvotes: 2

moonshadow
moonshadow

Reputation: 89065

What do you want the user to enter? parseFloat will parse integers, too. You could just always use that, and in the cases where you actually want to restrict yourself to working with integers, use Math.round() on the result.

Upvotes: 5

Robert Harvey
Robert Harvey

Reputation: 180788

It depends on how much rigor you need.

Where are you going to store it? Is it really your intention to switch the type if there's nothing after the decimal point? Or is it really just a float that looks like an integer?

Upvotes: 0

Related Questions