DecimalFormat

R

Roedy Green

If you wanted to trim trailing 0s from a string representation of a
number after the decimal point, can you do it directly with
DecimalFormat, or do you need to do String operations on the result?
 
J

John B. Matthews

Roedy Green said:
If you wanted to trim trailing 0s from a string representation of a
number after the decimal point, can you do it directly with
DecimalFormat, or do you need to do String operations on the result?

I'm pretty sure you'd have to convert the String to a Number, long or
double before you could format() it.
 
E

Eric Sosman

If you wanted to trim trailing 0s from a string representation of a
number after the decimal point, can you do it directly with
DecimalFormat, or do you need to do String operations on the result?

If you're starting with the numeric value (as opposed to an
already-generated String), just use the '#' pattern character, as

NumberFormat fmt = new DecimalFormat("#.##");

This will format 1.20 as "1.2" and 3.45 as "3.45".
 
R

Roedy Green

I'm pretty sure you'd have to convert the String to a Number, long or
double before you could format() it.

I have it as a double. DecimalFormat.format gives me the String.

My question is, is there any tricky pattern you can give it to trim
trailing 000, or do you need to process the output of .format as a
String?
 
R

Roedy Green

NumberFormat fmt = new DecimalFormat("#.##");

This will format 1.20 as "1.2" and 3.45 as "3.45".

Any is there a way to trim .00 to get rid of the dot too, or is that
the default behaviour?
 
R

Roedy Green

Any is there a way to trim .00 to get rid of the dot too, or is that
the default behaviour?

I found that .### works exactly as needed, dropping the dot for .000.
Thanks.
 

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
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top