在java中最多有两个十进制的地方?(复制)

时间:2021-11-27 17:10:33

This question already has an answer here:

这个问题已经有了答案:

I have read a lot of * questions but none seems to be working for me. i am using math.round() to round off. this is the code:

我读过很多*的问题,但似乎没有一个适合我。我正在使用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);
}
}

the output i get is: 123 but i want it to be 123.14. i read that adding *100/100 will help but as you can see i didn't manage to get it to work.

我得到的输出是:123但我想要的是123.14。我读到过增加*100/100会有帮助,但是正如你所看到的,我没能让它工作。

it is absolutely essential for both input and output to be a double.

输入和输出必须是双重的。

it would be great great help if you change the line 4 of the code above and post it.

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

12 个解决方案

#1


312  

Well this one works...

这一作品…

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

Output is

输出是

123.14

Or as @Rufein said

或@Rufein说

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

this will do it for you as well.

这对你也一样。

#2


66  

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));

#3


41  

String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}

#4


33  

BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);

#5


11  

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

回到你的代码,将100替换为100,并告诉我它是否有效。然而,如果你想要正式一点,可以试试以下方法:

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

#6


7  

I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00") or using Math.round(a * 100) / 100 .

我知道这是一个2岁的问题,但是因为每个人都面临着一个问题,在某个时间点的时候,要把它们的值取下来。我想分享一种不同的方法,通过使用BigDecimal类,我们可以得到任意标度的四舍五入值。圆(a * 100) / 100。

import java.math.BigDecimal;

public class RoundingNumbers {
    public static void main(String args[]){
        double number = 123.13698;
        int decimalsToConsider = 2;
        BigDecimal bigDecimal = new BigDecimal(number);
        BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with setting scale = "+roundedWithScale);

        bigDecimal = new BigDecimal(number);
        BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);

    }
}

This program would give us below output

这个程序会给出低于输出的结果

Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14

#7


6  

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

should be

应该是

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

Adding 'D' to 100 makes it Double literal, thus result produced will have precision

将“D”加到100会使它变成双倍的文字,因此产生的结果将具有精确性

#8


5  

Try :

试一试:

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);   }}

#9


4  

This is long one but a full proof solution, never fails

这是一个很长的问题,但它是一个完整的证明,永远不会失败

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;

把你的数字作为二重函数传递给这个函数,它会返回四舍五入小数的值,直到最近的值5;

if 4.25, Output 4.25

如果4.25,4.25输出

if 4.20, Output 4.20

如果4.20,4.20输出

if 4.24, Output 4.20

如果4.24,4.20输出

if 4.26, Output 4.30

如果4.26,4.30输出

if you want to round upto 2 decimal places,then use

如果你想四舍五入到小数点后两位,那就用

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

if up to 3 places, new DecimalFormat("#.###")

如果最多有3个位置,新建DecimalFormat(“### ###”)

if up to n places, new DecimalFormat("#.nTimes #")

如果最多有n个位置,新建小数格式(“#”)。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))));

            }

#10


3  

seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic. in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:

看起来你被整数算术击中了:在某些语言中(int)/(int)总是被作为整数算术计算。为了强制浮点运算,请确保至少有一个操作数是非整数的:

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

#11


1  

I just modified your code. It works fine in my system. See if this helps

我只是修改了你的代码。它在我的系统中运行良好。看看这有助于

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

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

    System.out.println(roundOff);
}
}

#12


0  

public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;
}

Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.

大多数情况下应该没问题。如果您希望与double兼容,您仍然可以更改类型。

#1


312  

Well this one works...

这一作品…

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

Output is

输出是

123.14

Or as @Rufein said

或@Rufein说

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

this will do it for you as well.

这对你也一样。

#2


66  

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));

#3


41  

String roundOffTo2DecPlaces(float val)
{
    return String.format("%.2f", val);
}

#4


33  

BigDecimal a = new BigDecimal("123.13698");
BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
System.out.println(roundOff);

#5


11  

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

回到你的代码,将100替换为100,并告诉我它是否有效。然而,如果你想要正式一点,可以试试以下方法:

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

#6


7  

I know this is 2 year old question but as every body faces a problem to round off the values at some point of time.I would like to share a different way which can give us rounded values to any scale by using BigDecimal class .Here we can avoid extra steps which are required to get the final value if we use DecimalFormat("0.00") or using Math.round(a * 100) / 100 .

我知道这是一个2岁的问题,但是因为每个人都面临着一个问题,在某个时间点的时候,要把它们的值取下来。我想分享一种不同的方法,通过使用BigDecimal类,我们可以得到任意标度的四舍五入值。圆(a * 100) / 100。

import java.math.BigDecimal;

public class RoundingNumbers {
    public static void main(String args[]){
        double number = 123.13698;
        int decimalsToConsider = 2;
        BigDecimal bigDecimal = new BigDecimal(number);
        BigDecimal roundedWithScale = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with setting scale = "+roundedWithScale);

        bigDecimal = new BigDecimal(number);
        BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
        System.out.println("Rounded value with Dividing by one = "+roundedValueWithDivideLogic);

    }
}

This program would give us below output

这个程序会给出低于输出的结果

Rounded value with setting scale = 123.14
Rounded value with Dividing by one = 123.14

#7


6  

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

should be

应该是

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

Adding 'D' to 100 makes it Double literal, thus result produced will have precision

将“D”加到100会使它变成双倍的文字,因此产生的结果将具有精确性

#8


5  

Try :

试一试:

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);   }}

#9


4  

This is long one but a full proof solution, never fails

这是一个很长的问题,但它是一个完整的证明,永远不会失败

Just pass your number to this function as a double, it will return you rounding the decimal value up to the nearest value of 5;

把你的数字作为二重函数传递给这个函数,它会返回四舍五入小数的值,直到最近的值5;

if 4.25, Output 4.25

如果4.25,4.25输出

if 4.20, Output 4.20

如果4.20,4.20输出

if 4.24, Output 4.20

如果4.24,4.20输出

if 4.26, Output 4.30

如果4.26,4.30输出

if you want to round upto 2 decimal places,then use

如果你想四舍五入到小数点后两位,那就用

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

if up to 3 places, new DecimalFormat("#.###")

如果最多有3个位置,新建DecimalFormat(“### ###”)

if up to n places, new DecimalFormat("#.nTimes #")

如果最多有n个位置,新建小数格式(“#”)。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))));

            }

#10


3  

seems like you are hit by integer arithmetic: in some languages (int)/(int) will always be evaluated as integer arithmetic. in order to force floating-point arithmetic, make sure that at least one of the operands is non-integer:

看起来你被整数算术击中了:在某些语言中(int)/(int)总是被作为整数算术计算。为了强制浮点运算,请确保至少有一个操作数是非整数的:

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

#11


1  

I just modified your code. It works fine in my system. See if this helps

我只是修改了你的代码。它在我的系统中运行良好。看看这有助于

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

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

    System.out.println(roundOff);
}
}

#12


0  

public static float roundFloat(float in) {
    return ((int)((in*100f)+0.5f))/100f;
}

Should be ok for most cases. You can still changes types if you want to be compliant with doubles for instance.

大多数情况下应该没问题。如果您希望与double兼容,您仍然可以更改类型。