| Author |
NuberFormat format and parse doubt
|
Leandro Coutinho
Ranch Hand
Joined: Mar 04, 2009
Posts: 415
|
|
Hi!
This question is from the book K&B Java6:
The output is:
987.12346
987.123456
I have two doubts:
1. Why it printed 6 instead of 5 in the first line?
2. If I parse with my default locale, the dot is not printed, but in the US it is. Why US prints dot when parsing?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
Leandro Coutinho wrote:
I have two doubts:
1. Why it printed 6 instead of 5 in the first line?
2. If I parse with my default locale, the dot is not printed, but in the US it is. Why US prints dot when parsing?
1. Take a look at the RoundingMode of the NumberFormat class. If you want it to just truncate, you'll need to set the mode correctly.
2. Well, in the U.S., the fractional portion of a number is separated by a period. This may not be true everywhere.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Leandro Coutinho
Ranch Hand
Joined: Mar 04, 2009
Posts: 415
|
|
Thanks for the reply!
Henry Wong wrote:
2. Well, in the U.S., the fractional portion of a number is separated by a period. This may not be true everywhere.
Ok, but the parse result should be equal to the format, right? The parse documentation says: "Parses text from the beginning of the given string to produce a number. ...", but the result is a wrong number.
Try this code:
The output is:
987,12346
987123456
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
Leandro Coutinho wrote:
Ok, but the parse result should be equal to the format, right? The parse documentation says: "Parses text from the beginning of the given string to produce a number. ...", but the result is a wrong number.
Yes, the parse() method should match the format() method. And in this case, it doesn't. You configured it for a region that uses a comma, and then you parsed it with a string that uses a period. Just as the comma is ignored in the US format, the period is ignored in the Brazil format.
As for the double side, that always uses a period. NumberFormat is for the string side only.
Henry
|
 |
Leandro Coutinho
Ranch Hand
Joined: Mar 04, 2009
Posts: 415
|
|
Henry Wong wrote:
Leandro Coutinho wrote:
Ok, but the parse result should be equal to the format, right? The parse documentation says: "Parses text from the beginning of the given string to produce a number. ...", but the result is a wrong number.
Yes, the parse() method should match the format() method. And in this case, it doesn't. You configured it for a region that uses a comma, and then you parsed it with a string that uses a period. Just as the comma is ignored in the US format, the period is ignored in the Brazil format.
As for the double side, that always uses a period. NumberFormat is for the string side only.
Henry
of course!!
thank you!!
|
 |
 |
|
|
subject: NuberFormat format and parse doubt
|
|
|