简体   繁体   English

如何知道float值是否大于Integer.MAX_VALUE?

[英]How to know if the float value is greater than Integer.MAX_VALUE?

// The given input
String input = "99999999.99";

// We need only 2 decimals (in case of more than 2 decimals is in input)
Float value = Float.valueOf(input);
DecimalFormat df = new DecimalFormat("#0.00");
input = df.format(value);
value = new Float(input);

// Now we have a clear 2 decimal float value
// Check for overflow
value *= 100; // Multiply by 100, because we're working with cents

if (value >= Integer.MAX_VALUE) {
   System.out.println("Invalid value");
}
else {
///
}

The statement doesn't work, the condition fails. 该语句不起作用,条件失败。

Which is the correct way to compare a float with an integer value? 比较浮点数和整数值的正确方法是哪种?

There is nothing wrong with your code. 您的代码没有错。 99999999.99 times 100 equals to 9999999999 . 99999999.99乘以100等于9999999999。 That's larger that max int == 2147483647 (it's 2^31 -1). 大于max int == 2147483647 (即2 ^ 31 -1)。 If you want to be able to store bigger integer numbers use long . 如果您希望能够存储更大的整数,请使用long

Elaborate further if it's not your problem. 如果不是您的问题,请进一步详细说明。

try this : 尝试这个 :

public static void main(final String[] args) {
    // The given input
    String input = "99999999.99";

    // We need only 2 decimals (in case of more than 2 decimals is in input)
    Float value = Float.parseFloat(input);
    DecimalFormat df = new DecimalFormat("#0.00");
    DecimalFormatSymbols custom = new DecimalFormatSymbols();
    custom.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(custom);
    input = df.format(value);
    value = new Float(input);

    // Now we have a clear 2 decimal float value
    // Check for overflow
    value *= 100; // Multiply by 100, because we're working with cents

    if (value >= Integer.MAX_VALUE) {
        System.out.println("Invalid value");
    } else {
        ///
    }
}

Have a nice day 祝你今天愉快

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

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