Formatting double to 2 decimals doesn't work

2019-02-28 01:56发布

I want to round this double:

3.499999999999999

to:

3.50

And I already used these two methods:

DecimalFormat df = new DecimalFormat("0.00");
        double result = Double.valueOf(df.format(input));
        System.out.println(answer);

and

public double round(double input)
    {
        int decimalPlace = 2;
        BigDecimal bd = new BigDecimal(input);
        bd = bd.setScale(decimalPlace,BigDecimal.ROUND_UP);

        return (bd.doubleValue());
    }

But It keeps printing:

3.5

Does anyone have a solution for this? Because I really think that this should work. Thanks for your help.

4条回答
戒情不戒烟
2楼-- · 2019-02-28 02:26

Your first solution is really, really close. Just do this:

    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println(df.format(input));

The reason your version doesn't work is that you're taking the input double, formatting it as a String with 2dp, but then converting it back to a double. System.out.println is then printing the double as it always would, with no special decimal-place rules.

查看更多
再贱就再见
3楼-- · 2019-02-28 02:31

You can use Precision class of apache commons-math

double result = Precision.round(3.499999999999999, 2);
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-28 02:40

Did you try replacing the 0's with #'s?

DecimalFormat df = new DecimalFormat("#.##"); System.out.println(df.format(input));

According to here the # will be resolved to 0 if the digit is absent

查看更多
太酷不给撩
5楼-- · 2019-02-28 02:41

You can use the printf formatting which may be simpler.

System.out.printf("%.2f%n", 3.5);

prints

3.50
查看更多
登录 后发表回答