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'.
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'.
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;
}
}
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.
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