我读过很多关于stackoverflow的问题,但似乎没有一个对我有用。我使用math.round()来四舍五入。 这是代码:

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100;

    System.out.println(roundOff);
}
}

我得到的输出是:123,但我希望它是123.14。我读到添加*100/100会有帮助,但正如你所看到的,我没有设法让它工作。

输入和输出都是double是绝对必要的。

如果您更改上面代码的第4行并发布它,将会有很大的帮助。


当前回答

这是一个很长的解决方案,但完全证明,从来不会失败

只要把你的数字作为双精度值传递给这个函数,它就会返回你四舍五入到十进制值的最近值5;

如果4.25,输出4.25

如果4.20,输出4.20

如果4.24,输出4.20

如果4.26,输出4.30

如果你想四舍五入到小数点后2位,那么使用

DecimalFormat df = new DecimalFormat("#.##");
roundToMultipleOfFive(Double.valueOf(df.format(number)));

如果最多3个位置,新建DecimalFormat("#.###")

如果多达n个位置,则新建DecimalFormat("#. # ")。nTimes #”)

 public double roundToMultipleOfFive(double x)
            {

                x=input.nextDouble();
                String str=String.valueOf(x);
                int pos=0;
                for(int i=0;i<str.length();i++)
                {
                    if(str.charAt(i)=='.')
                    {
                        pos=i;
                        break;
                    }
                }

                int after=Integer.parseInt(str.substring(pos+1,str.length()));
                int Q=after/5;
                int R =after%5;

                if((Q%2)==0)
                {
                    after=after-R;
                }
                else
                {
                   if(5-R==5)
                   {
                     after=after;
                   }
                   else after=after+(5-R);
                }

                       return Double.parseDouble(str.substring(0,pos+1).concat(String.valueOf(after))));

            }

其他回答

BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);
String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}

我只是修改了你的代码。它在我的系统中工作得很好。看看这是否有用

class round{
    public static void main(String args[]){

    double a = 123.13698;
    double roundOff = Math.round(a*100)/100.00;

    System.out.println(roundOff);
}
}

回到你的代码,用100.00替换100,让我知道它是否有效。 然而,如果你想要正式一点,试试这个:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

试一试:

class round{
public static void main(String args[]){

double a = 123.13698;
double roundOff = Math.round(a*100)/100;
String.format("%.3f", roundOff); //%.3f defines decimal precision you want
System.out.println(roundOff);   }}