简体   繁体   中英

Convert double to int without rounding java

我想知道如何在 Java 中不四舍五入的情况下将 double 转换为 int,例如 3,9 double 到 39 int,提前致谢!

I guess you could convert your double to a String , remove the . and than try to parse it to an int .

By doing something like this:

public static void main(String[] args) {
    double input = 2.12345;
    String stringInput = String.valueOf(input);
    String withoutDot = stringInput.replace(".", "");

    try {
        int number = Integer.parseInt(withoutDot);
    }
    catch (NumberFormatException e) {
        // Handle this exception gracefully
    }
}

Be aware that with this solution you will always have a NumberFormatException when your double value has to many decimal points.

If your double values always have the same amount of decimal points (2 for example) another solution would be to use multiplication:

public static void main(String[] args) {
    double input = 2.12;
    Double rounded = 2.12 * 100;
    int number = rounded.intValue();
}

In general it's impossible. Because double can have much more digits then int.

    double d = 3.111111111111111111111111111111;
    System.out.println(Integer.MAX_VALUE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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