Parsing Input
Number formats also handle
input. When
used for input, a number format converts a string in the appropriate
format to a binary number, achieving more flexible conversions than
you can get with the methods in the type wrapper classes (like
Integer.parseInt()
). For instance, a percent
format parse()
method can interpret 57% as 0.57
instead of 57. A currency format can read (12.45) as -12.45.
There are three parse()
methods in the
NumberFormat
class. All do roughly the same thing:
public Number parse(String text) throws ParseException public abstract Number parse(String text, ParsePosition parsePosition) public final Object parseObject(String source, ParsePosition parsePosition)
The first parse()
method attempts to parse a
number from the given text. If the text represents an integer,
it’s returned as an instance of
java.lang.Long
. Otherwise, it’s returned as
an instance of java.lang.Double
. If a string
contains multiple numbers, only the first one is returned. For
instance, if you parse “32 meters” you’ll get the
number 32 back. Java throws away everything after the number
finishes. If the text cannot be interpreted as a number in the given
format, a ParseException
is thrown. The second
parse()
method specifies where in the text parsing
starts. The position is given by a ParsePosition
object. This is a little more complicated than using a simple
int
but does have the advantage of allowing one to
read successive numbers from the same string. The third
parse()
method merely ...
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.