2016-12-21 4 views
0
// 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 { 
/// 
} 

ステートメントが機能せず、条件が失敗します。浮動小数点値がInteger.MAX_VALUEより大きいかどうかを知る方法?

floatと整数値を比較する正しい方法はどれですか?

+0

注意を持っています。あなたがお金を処理している場合は、可能であれば浮動小数点数の使用を避けるべきです。 –

答えて

3

コードに問題はありません。 99999999.99回100は9999999999に等しくなります。 これは、max int == 2147483647(それは2^31 -1です)より大きいです。より大きな整数を格納できるようにしたい場合は、longを使用してください。

あなたの問題ではない場合、さらに詳しく説明してください。

1

これを試してみてください。

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 { 
     /// 
    } 
} 

はFloat` `の精度は` Integer`の完全な範囲を処理するのに十分ではないという素敵な一日

+0

使用する小数点記号が '、' –

関連する問題