Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formatting a string 1

Status
Not open for further replies.

developer155

Programmer
Jan 21, 2004
512
US
Hi, I need to formatt a string (the string reperesents a price and it is stored in the database with one zero after the whole part, like 30.0). I need it to have 2 zeros (30.00). here is what I am doing:

String cost;
cost=database.getCost();//this ghets cost from db
String pattern="00.00";
DecimalFormat myFormatter = new DecimalFormat(pattern);
cost = myFormatter.format(cost);

I am getting an error that I am passing an object and that is incorrect. I see that I am passign a String object into format function, but what shoudl I do? Any ideas how to fix this or how to do what I need to do in some other way?

thanks!
 
What object does "database.getCost()" return ?
 
Sorry Sedj, here it is

java.lang.IllegalArgumentException: Cannot format given Object as a Number
at java.text.NumberFormat.format(NumberFormat.java:202)
at java.text.Format.format(Format.java:129)
at
..Call Stack
at java.lang.Thread.run(Thread.java:479)
exception: Cannot format given Object as a NumberTue May 25 02:59:56 2004: ==========================================
Tue May 25 02:59:56 2004: End of output for a property [139214.1].


thanks
 
I imagine that the result from "database.getCost()" is not a *number*. Print out what it is before you format it to debug what is actually coming back :

cost=database.getCost();
System.err.println("!!!!! cost is " +cost);
 
I ran the program in debugger and the cost is "50.0", its a string.

thanks
 
Found it ...

Code:
Double dCost = new Double(database.getCost());
String pattern="00.00";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String cost = myFormatter.format(dCost);

System.err.println(cost);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top