Reputation: 4543
Let's consider below code snippet
public static void main(String[] args) {
DecimalFormat twoDForm = new DecimalFormat("#.00");
double k=4.144456;
System.out.println(twoDForm.format(k));
}
I was expecting output as 4.15 as if we consider iterative rounding, the answer should be 4.15, but I guess DecimalFormat
checks only immediate next digit value while rounding.
Is there any way by which I can achieve iterative rounding output.
Upvotes: 0
Views: 54
Reputation: 26185
The question calls for a unique rounding mode. This answer addresses the general issue of getting special rounding.
The BigDecimal(double)
constructor and BigDecimal's toString()
method are both exact.
BigDecimal bd = new BigDecimal(d);
String s = bd.toString();
leaves s
with an exact, unrounded, String
representation of double
d
. You can then do any required string manipulation to get the value you want. In addition, you can use any of the BigDecimal
rounding modes in rounding bd
.
Upvotes: 2