6 Replies Latest reply on Aug 1, 2007 8:02 PM by 796254

# number format

I have

String num = "123.33"
String num1 = "123.9"

if i want to display like

\$123.33
or
\$123.90

How can i do that?
• ###### 1. Re: number format
I have

String num = "123.33"
String num1 = "123.9"

if i want to display like

\$123.33
or
\$123.90

How can i do that?
Start by turning those Strings into doubles.

Then use NumberFormat.
``````String num = "123.90";
double x = Double.valueOf(num);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(x));``````
%
• ###### 2. Re: number format
is there any way to keep two decimal point without using double?
• ###### 3. Re: number format
is there any way to keep two decimal point without using double?
You have no idea what you're doing. The number of decimal points should be purely a display condition. NumberFormat is the way to accomplish that.

If you don't understand how floating point numbers work, maybe you should read this:

http://docs.sun.com/source/806-3568/ncg_goldberg.html

%
• ###### 4. Re: number format
just thought i'd add that this works as well:
``````          double money = 3.55;
DecimalFormat nf = new DecimalFormat("\$0.00");
System.out.println(nf.format(money));``````
• ###### 5. Re: number format
is there any way to keep two decimal point without
using double?
of course. you could store the amount as a string or use BigDecimal and define the precision. but the response about floating point issues are real and you need to be aware of them because they will inevitably get you!
• ###### 6. Re: number format
just thought i'd add that this works as well:
``````          double money = 3.55;
DecimalFormat nf = new DecimalFormat("\$0.00");
System.out.println(nf.format(money));``````
I don't know if this method can adapt to different Locales, but NumberFormat.getCurrencyInstance() does.

%