donnyton
donnyton

Reputation: 6054

Advanced rounding options with BigDecimal

I am writing a program that has to round very large and precise numbers (possibly many more significant digits than even double could handle), and am using BigDecimals.

Is there a way to make BigDecimal round based on place and not significant figures?

That is, I need 0.5 to round to 1 and 0.4 to round to 0, but since they are the same number of significant figures, BigDecimal refuses to round either of them.

Upvotes: 2

Views: 720

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502825

I suspect you want setScale:

import java.math.*;

public class Test
{
    public static void main(String[] args)
    {
        showRounded(new BigDecimal("0.4"));
        showRounded(new BigDecimal("0.5"));
    }

    static void showRounded(BigDecimal input)
    {
        BigDecimal output = input.setScale(0, BigDecimal.ROUND_HALF_UP);
        System.out.println(input + " => " + output);
    }
}

Upvotes: 6

Related Questions