How to suppress final 0 with DecimalFormat?

A

Adam Lipscombe

Folks,

I need to output a blank if a double is 0.0;

If I use DecimalFormat to format a zero double I get a single "0" output.
i.e.

double d = 0.0;
DecimalFormat dF = new DecimalFormat("#.##");
System.out.println(dF.format(d));

gives "0".


How do I get rid of the zero?


TIA -Adam
 
J

John C. Bollinger

Adam said:
Folks,

I need to output a blank if a double is 0.0;

If I use DecimalFormat to format a zero double I get a single "0" output.
i.e.

double d = 0.0;
DecimalFormat dF = new DecimalFormat("#.##");
System.out.println(dF.format(d));

gives "0".


How do I get rid of the zero?

Write your own NumberFormat implementation: what you want is not
possible with DecimalFormat. Make your NumberFormat's parse() method
transform blanks back into zeroes, for otherwise it will be broken. Do
make sure you appreciate the implications for error detection during
parsing.


John Bollinger
(e-mail address removed)
 
V

Virgil Green

Adam Lipscombe said:
Folks,

I need to output a blank if a double is 0.0;

If I use DecimalFormat to format a zero double I get a single "0" output.
i.e.

double d = 0.0;
DecimalFormat dF = new DecimalFormat("#.##");
System.out.println(dF.format(d));

gives "0".


How do I get rid of the zero?

System.out.println(d == 0 ? "" : dF.format(d));

- Virgil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top