Bootstrap

Java 将double转换为int—使用Math.round()避免出现精度丢失

Math.round()方法会将浮点值四舍五入到最接近的long值。然后我们可以将其转换为int类型。

我在下面给出了一个简单的Java程序,该程序显示了如何使用Math.round()方法将double转换为int 。

/ ** 
 *使用java将double转换为int的Java程序 
 * Math.round()方法,四舍五入
 ** /
 public class DoubleToIntUsingRoundMethod{
     public static void main(String []args){

        // 情况1
        double doubleValue = 82.14; // 82.14
        System.out.println("doubleValue: "+doubleValue);
        //将case双精度型转换为int
        int intValue = (int) Math.round(doubleValue); // 82
        System.out.println("intValue: "+intValue);
        System.out.println();

        // 情况2
        double nextDoubleValue = 82.99; // 
        System.out.println("nextDoubleValue: "+nextDoubleValue);
        // Math.round(nextDoubleValue)返回long值
        //将case的类型转换为int
        int nextIntValue = (int) Math.round(nextDoubleValue);    // 83
        System.out.println("nextIntValue: "+nextIntValue);              
     }
}


输出:
doubleValue:82.14
整数值:82
nextDoubleValue:82.99
nextIntValue:83