Decimal Format Problem
Any help on this would be greatly appreciated. Could someone please examine the code below and tell me why it does not throw an exception when parsing numbers not fitting the proper format? Thanks.
import java.text.*;
class TestFormat
{
public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(4);
df.setMaximumIntegerDigits(3);
df.setMinimumFractionDigits(4);
df.setMinimumIntegerDigits(3);
Db.p("Format object: " + df.toPattern());
ParsePosition index = new ParsePosition(0);
for (short i = 0; i < args.length; ++i)
{
try
{
index.setIndex(0);
Object number = df.parseObject(args, index);
Db.p("Parsed OK: " + args + ' ' + number + "; position: " + index.getIndex());
}
catch (Exception e)
{
Db.p("Parse failed: " + args);
Db.p(e);
}
}
}
}
[1011 byte] By [
Mass666] at [2007-9-26 4:48:10]

(I have been waiting hoping someone would provide a better explaination.)
I tried it with 8001.23456 and it took it with no problem also. And it returned the same number too.
With SimpleDateFormat there is a setLenient feature which at leasts suggests that there was some consideration of validating dates. There is no such thing on the number format classes.
I am not fully convinced that 1.23 is not the same as 001.2300. But it really should do something with 8001.23456.
Some possibilities:
-Enter it in as a bug in the bug database.
-Get the source code and use it as a base to create a class that does validate.
Right, DecimalFormat is completely relaxed about digit count settings when parsing. If you need strict picture-type checking, you have to write it yourself. (It would be nice to be able to enable something like that).
Regardless of that, the code example above will not catch ANY parsing error (except, of course, a null source string in args<i>). Forms of the parse or parseObject methods that take a ParsePosition argument do not throw parsing-related exceptions. They instead return null and set the errorIndex value in the ParsePosition object appropriately.
>They instead return null and set the errorIndex value
Ok. But in this case it seems the only thing that is an error is if the item being parsed is not a number at all. The formatting info is completely ignored.
From the java docs for SimpleDateFormat
SimpleDateFormat is a concrete class for formatting and parsing dates ...
The java docs for DecimalFormat
DecimalFormal ...features designed to make it possible to parse and format numbers ...
Although not exactly the same SimpleDateFormat does allow one to validate input. While one might as well not bother using DecimalFormat/NumberFormat for the same task.