Sachin Mhetre
Sachin Mhetre

Reputation: 4543

Java: Rounding UP double value in iterative manner

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

Answers (1)

Patricia Shanahan
Patricia Shanahan

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

Related Questions