How do I prevent String.format("%.2f", doubleValue);
from rounding off (round half up algorithm) instead of just truncating it?
e.g.
doubleValue = 123.459
after formatting,
doubleValue = 123.46
I just want to discard the last digit,
123.45
I know there are other ways to do this, I just want to know if this is possible using the String.format.
2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).
2f' means round to two decimal places. This format function returns the formatted string. It does not change the parameters.
If the value to be formatted has more than the specified or default number of decimal places, the fractional value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero.
The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: The value of i is: 461012. The printf and format methods are overloaded.
You can always set the rounding mode:
http://java.sun.com/javase/6/docs/api/java/math/RoundingMode.html
and then use String.Format() HALF_EVEN is used by default, but you can change it to CEILING
another no so flexible approach will be (but this is not what you asked about):
DecimalFormat df = new DecimalFormat("###.##");
df.format(123.459);
Looks like the answer is a big fat NO. http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#dndec "then the value will be rounded using the round half up algorithm"
I find it odd they'd do that, since NumberFormatter allows you to set RoundingMode. But as you say, there's other ways to do it. The obviously easiest being subtract .005 from your value first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With