tags:

views:

140

answers:

5

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?

A: 

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?

Robert Harvey
I'm doing the shunting-yard algorithm. The user can enter either in a given expression. For example: ((5+3) * 8.2)). When I'm evaluating this expression (after converting it to RPN), I need to parse it to the appropriate type so it evaluates correctly.
KingNestor
+5  A: 

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.

moonshadow
+2  A: 

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
Matt Briggs
+1  A: 

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.

Lucero
I was mistaken in thinking they would resolve to two different types. I see now from Matt Briggs answer that that is not the case.
KingNestor
+1  A: 

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;
CMS
+1 for suggesting the unary plus operator, that's what immediately sprang to my mind and much easier than using parseFloat.
Andy E