Link to home
Start Free TrialLog in
Avatar of dds110
dds110

asked on

Format a string as currency

Hi.  Yes this is classwork but I'm not asking anyone to do it.  In fact, it's done.  Except for formatting one field as currency.  This is not a requirement of my program, I just want to do it.  The data I have is String.  It is the price of a book.  How do I format it to currency?

Thanks
Avatar of Zeroshade
Zeroshade

If the price is declared as a string you could run a loop through the string using .charAt(). Then add a dollar sign at the first character and decimal into the string before the last 2 characters.
How about:

//assume bookprice contains the string you have
//which I assume is an ASCII string of digits
String price="$"+bookprice.substring(0,bookprice.length()-2)+"."+bookprice.substring(bookprice.length()-2);
Avatar of CEHJ
Try

double price = 2.989;
String symbol = NumberFormat.getCurrency().getSymbol();
NumberFormat nf = NumberFormat.getInstance();
System.out.println(symbol + nf.format(price));
>>NumberFormat nf = NumberFormat.getInstance();

should have been

>>NumberFormat nf = NumberFormat.getCurrencyInstance();
Avatar of dds110

ASKER

I have done the first two suggestions.  The suggestion from CEHJ, I'm sure it works but, the data is String: not double.  Isn't there a way to "TypeCast" one data type to another?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of quickhippo
quickhippo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is all you need actually:

String price = "2.989";
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println(nf.format(Double.parseDouble(price)));
Avatar of dds110

ASKER

quickhippo and CEHJ get the points for this.  Both suggestions were ok.  The points for this Q will go to quickhippo.  CEHJ, Look for a new post for your points.

Thanks