aspose file tools*
The moose likes Beginning Java and the fly likes Reading Currency Values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reading Currency Values" Watch "Reading Currency Values" New topic
Author

Reading Currency Values

Roberto Diaz
Ranch Hand

Joined: Mar 08, 2002
Posts: 40
I am trying to read 'Dollar' values.
Here is the code which reads the values from
the keyboard :
***********
System.out.print("Enter the cost of the product : ");
BufferedReader consoleIn =
new BufferedReader(new InputStreamReader(System.in));
String Input = consoleIn.readLine();
ActualCost = Double.parseDouble(Input);
**********
This works fine except when I preceede the
numbers with a '$' sign.
Is there a turnaround for this.
I tried using 'NumberFormat',no luck tho.
What am I missing ?
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Hello,
Double.parseDouble(String) is looking for a number only - it doesn't know what to do with a dollar sign.
You could parse the input String and remove any dollar signs before you do a Double.parseDouble(String).
Look at the String documentation and the subString(int) method.
You could still have troubles even after removing the '$' - what if the input String were "$$123.34c"?
You might want to explore catching exceptions.
Good Luck,
-Dirk Schreckmann


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Actually you should use a NumberFormat object.
NumberFormat cf = NumberFormat.getCurrencyInstance();
//then some optional calls to set up your exact currency format patterns, or use the locale defaults.
Then...
Number parsedNumber = cf.parse(input ); //PLEASE DO NOT CAPITALIZE YOUR VARIABLE NAMES, THEY LOOK LIKE THEY ARE CLASS IDENTIFIERS.
Then you can call various methods of Number to get out an actual number...probably parsedNumber.doubleValue();


Rob
SCJP 1.4
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Hello,
Yep, I prefer that style also. Though, were I a beginner, I'd tell you to take a hike trying to get me to use an Abstract class and all that other jazz.
And you still could have issues with exception handling:
NumberFormat.parse(String) throws ParseException if the beginning of the specified string cannot be parsed.
Good Luck,
-Dirk Schreckmann
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reading Currency Values