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
Thanks
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.substr ing(0,book price.leng th()-2)+". "+bookpric e.substrin g(bookpric e.length() -2);
//assume bookprice contains the string you have
//which I assume is an ASCII string of digits
String price="$"+bookprice.substr
Try
double price = 2.989;
String symbol = NumberFormat.getCurrency() .getSymbol ();
NumberFormat nf = NumberFormat.getInstance() ;
System.out.println(symbol + nf.format(price));
double price = 2.989;
String symbol = NumberFormat.getCurrency()
NumberFormat nf = NumberFormat.getInstance()
System.out.println(symbol + nf.format(price));
>>NumberFormat nf = NumberFormat.getInstance() ;
should have been
>>NumberFormat nf = NumberFormat.getCurrencyIn stance();
should have been
>>NumberFormat nf = NumberFormat.getCurrencyIn
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
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
This is all you need actually:
String price = "2.989";
NumberFormat nf = NumberFormat.getCurrencyIn stance();
System.out.println(nf.form at(Double. parseDoubl e(price))) ;
String price = "2.989";
NumberFormat nf = NumberFormat.getCurrencyIn
System.out.println(nf.form
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
Thanks