格式化双精度到2位小数不起作用 [英] Formatting double to 2 decimals doesn't work

查看:124
本文介绍了格式化双精度到2位小数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  3.499999999999999 

to:

  3.50 

我已经使用了这两种方法:

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

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

return(bd.doubleValue());
}

但是它保持打印:

  3.5 

有没有人有这个解决方案?因为我真的认为这应该是正常的。感谢您的帮助。

解决方案

您的第一个解决方案真的很真实。只要这样做:

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

您的版本不起作用的原因是您正在使用输入 double,将其格式化为一个 String 与2dp,然后将其转换回 double System.out.println 然后像往常一样打印 double ,没有特殊的小数位数规则。 / p>

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.

解决方案

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.

这篇关于格式化双精度到2位小数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆