// 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 {
///
}
该语句不起作用,条件失败。
比较具有整数值的浮子的正确方法?
您的代码没有错。999999999.99乘以100等于999999999。比max int == 2147483647
(2^31 -1)更大。如果您想能够存储较大的整数使用long
。
如果不是您的问题,请进一步详细说明。
尝试以下:
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 {
///
}
}
祝您有美好的一天