I want to keep 2 fraction digits for double values. What is the best way to do it to avoid changing the values to a non-numeric String? For example, when I use NumberFormat.format, it changed 1576.73 to 1,576.73 which can't not be used for further calculation. When I used DecimalFormat.format, it also generated some non-numeric characters in the value so that I can't use Double.parseDouble() to change the final string to a double value. Thanks.
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
It kinda depends on what you're trying to do. Are you doing a bunch of calculations and want to print the final answer? You want to print intermediate answers? You want to do calculations and round off the answers before you do more calculations (You might run into some inaccuracies that way)? Are you working with money?
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Arfoo Huang
Ranch Hand
Joined: Jul 30, 2002
Posts: 31
posted
0
It was because I needed to print some values, and some of those values might be used for further calculation. I think I'll just format the data only when I need to print them. Thank you for the help.
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
posted
0
The easiest thing is to avoid parsing the number string in the first place. E.g. if you start with a double 1576.73 and you format it as the String 1,576.73, it might be nice to simply keep the original double in memory as 1576.73, so you don't have to parse it again. If that's not possible (e.g. if you're later in a completely different part of the program and the only way to recover the number is by reading a file or something) then go ahead and parse. But try using the parse(String) method of the NumberFormat class (or DecimalFormat) rather than Double.parseDouble(). It should be able to reverse the format for whatever particular decimal format you've created - while parseDouble() expects a standard format which is not necessarily the same as what you've created.
"I'm not back." - Bill Harding, Twister
John Lee
Ranch Hand
Joined: Aug 05, 2001
Posts: 2545
posted
0
Originally posted by Arfoo Huang: For example, when I use NumberFormat.format, it changed 1576.73 to 1,576.73 which can't not be used for further calculation.
Is it possible to change them back for calculation.