Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Number Format

 
Arfoo Huang
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Arfoo Huang
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John Lee
Ranch Hand
Posts: 2545
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic