Double d = 12.34567;
I want this String: "12.35" and this Double: 12.35
Double d = 12;
I want this String: "12.00" and this Double: 12
To get the strings, see java.text.DecimalFormat. Specifically:
DecimalFormat fmt = new DecimalFormat();
fmt.setMinimumFractionDigits(2);
fmt.setMaximumFractionDigits(2);
String str = fmt.format(12.34567);
Getting a Double is more difficult, and it's unclear what you want.
Doubles in Java are not stored in BCD, but rather as binary floating-
point numbers, so it makes no sense to talk about truncating them to a
certain number of decimal digits. Any given two decimal place decimal
number may or may not even be exactly representable as a float; it may
actually be a repeating decimal instead.
However, while there is not guaranteed to be a double that's exactly
equal to 12.35, there *is* guaranteed to be a double that will be
converted to "12.35" by methods such as Double.toString, String.valueOf,
and so forth. The easiest way to get that is to do the String
conversion above, and then use Double.parseDouble to get a double back
out (or Double.valueOf if you need a Double instead). Just be aware
that the value of the result may not be exactly 2.35; it will be the
double value nearest to 2.35 that can be exactly represented in binary
floating point.
(I'm using 2.35 merely as an example above, so when I say "may not" or
"may", I certainly *don't* mean that the behavior is undefined. Rather
I mean that it's perfectly well defined for a given value; but changing
2.35 to a different value could change those facts.)
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation