Re: Clean way to write Double into String without the trailing ".0"
?
On 12/21/2009 4:49 PM, abc wrote:
Eric Sosman wrote:
....
String s = Double.toString(x);
s = s.replaceAll((String)"\\.0$", "");
Perhaps it shows my age, but something inside me cringes
at the notion of wheeling out the regular expression cannon to
kill so simple a canary.
Same here, hence my question.
s = s.substring(s.indexOf('.'));
Wouldn't this get rid of the decimal fraction part completely, whether
it's non-zero or not? That's not what I want.
Actually, I botched the substring() call, and ought
to have written
s = s.substring(0, s.indexOf('.'));
.... and yes, this version would snip the decimal point and
everything that follows. That's what I thought you wanted,
but on re-reading your message I see that you only wanted to
jettison a literal ".0" and keep other fractional parts.
(I've obviously been hitting the eggnog too hard today ...).
In penance, here's another possibility:
if (s.endsWith(".0"))
s = s.substring(s.length() - 2);
"Cleaner" -- and certainly more flexible -- alternatives are
to use a java.text.DecimalFormat or a java.util.Formatter instead
of toString().
Thanks, I'll read up on those.
Probably the best course, since they'll also spare you
from unpleasantnesses like "10.333333333333334". Note that
PrintStream has convenience methods for using Formatter.
--
Eric Sosman
esosman@ieee-dot-org.invalid