tags:

views:

271

answers:

3

Hi all is there a way to find if the value parsed and returned by java.io.StreamTokenizer.nval (e.g. 200) was an integer or a floating number ?

Thanks

Edited:

I want to be able to know if the input was '200' or '200.0'.

A: 

I would use the modulus operator:

if (yourNval % 1 > 0)
{
    // nval is floating point.
}
else
{
    // nval is an integer.
}

This works because modulus works with floating point numbers in Java as well as integers.

UPDATE: Since you specify a need to distinguish integers from doubles with zero-value decimal portions, I think you'll have to do something like the following:

Double(yourNval).toString().indexOf('.');

So a more-complete function will look like:

if (yourNval % 1 > 0)
{
    // nval is floating point.
}
else
{
    // nval is an integer.

    // Find number of trailing zeroes.
    String doubleStr = Double(yourNval).toString();
    int decimalLoc = doubleStr.indexOf('.');
    int numTrailingZeroes = 0;

    if (decimalLoc > 0)
    {
        numTrailingZeroes = doubleStr.length() - decimalLoc - 1;
    }
}
pianoman
Thanks for your anwser, but this doesn't tell me if the input was '200.0' or '200'.
Pierre
I've added code above to determine the number of trailing zeroes an integer `nval` input contains. Your example, `200.0`, will result a `numTrailingZeroes` value of `1`.
pianoman
Thanks again, again your solution uses the float value but doesn't tell me about the original token parsed by the StreamTokenizer .
Pierre
If you know the integer value and the number of trailing zeroes, you know exactly what the token was. I guess akf and myself really just don't understand your question then, since you've had to rephrase it twice.
pianoman
A: 

As you are essentially trying to figure out if a double is an int or not, you can create a BigDecimal and test its scale() method. You could also use the Math static method floor() and test the return value against the original.

 if(Math.floor(myStreamTokenizer.nval) == myStreamTokenizer.navl)) {
     //treat it as an int
 } else {
     //treat it as a double
 }

Of the two, I would use the Math.floor option, as it would be more efficient.

akf
Thanks for your anwser, but this doesn't tell me if the input was '200.0' or '200'.
Pierre
as the field is a double, `200` will always be `200.0`.
akf
+1  A: 

I don't think it is possible with StringTokenizer, it's too old. You can use Scanner to do the job:

Scanner fi = new Scanner("string 200 200.0");
fi.useLocale(Locale.US);

while (fi.hasNext()) {
    if (fi.hasNextInt()) {
        System.out.println("Integer: " + fi.nextInt());
    } else if (fi.hasNextDouble()) {
        System.out.println("Double: " + fi.nextDouble());
    } else {
        System.out.println("String: " + fi.next());
    }  
}

Documentation for the class is here

tulskiy