繁体   English   中英

舍入一个double将其转换为int(java)

[英]Rounding a double to turn it into an int (java)

现在我正在尝试这个:

int a = round(n);

其中ndouble但它不起作用。 我究竟做错了什么?

片段中round()方法的返回类型是什么?

如果这是Math.round()方法,则在输入参数为Double时返回Long。

因此,您必须转换返回值:

int a = (int) Math.round(doubleVar);

如果你不喜欢Math.round(),你也可以使用这个简单的方法:

int a = (int) (doubleVar + 0.5);

double舍入为“最接近”的整数,如下所示:

1.4 - > 1

1.6 - > 2

-2.1 - > -2

-1.3 - > -1

-1.5 - > -2

private int round(double d){
    double dAbs = Math.abs(d);
    int i = (int) dAbs;
    double result = dAbs - (double) i;
    if(result<0.5){
        return d<0 ? -i : i;            
    }else{
        return d<0 ? -(i+1) : i+1;          
    }
}

您可以根据需要更改条件(结果<0.5)

import java.math.*;
public class TestRound11 {
  public static void main(String args[]){
    double d = 3.1537;
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP);
    // output is 3.15
    System.out.println(d + " : " + round(d, 2));
    // output is 3.154
    System.out.println(d + " : " + round(d, 3));
  }

  public static double round(double d, int decimalPlace){
    // see the Javadoc about why we use a String in the constructor
    // http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(double)
    BigDecimal bd = new BigDecimal(Double.toString(d));
    bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
  }
}

Math.round函数重载当它收到一个浮点值时,它会给你一个int。 例如,这可行。

int a=Math.round(1.7f);

当它收到一个double值时,它会给你一个long,因此你必须将它强制转换为int。

int a=(int)Math.round(1.7);

这样做是为了防止精度损失。 你的double值是64位,但是你的int变量只能存储32位,所以它只是将它转换为long,即64位,但你可以将它转换为32位,如上所述。

Math.round文档说:

返回将参数舍入为整数的结果 结果相当于(int) Math.floor(f+0.5)

无需转换为int 也许它从过去改变了。

public static int round(double d) {
    if (d > 0) {
        return (int) (d + 0.5);
    } else {
        return (int) (d - 0.5);
    }
}

你真的需要发布一个更完整的例子,所以我们可以看到你想要做的事情。 根据您发布的内容,这是我能看到的内容。 首先,没有内置的round()方法。 你需要调用Math.round(n) ,或者静态导入Math.round ,然后像你一样调用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM