2016-05-24 2 views
-1

я есть это const:Cast BigDecimal Const в целое

public static final BigDecimal IND = BigDecimal.valueOf(1); 

я хочу использовать его на switch заявление, как это:

int value = key.getCision().intValue(); 
switch (value) { 
    case PreEtat.IND: 
    //****** 
    break; 
    //**** 
    default: 
    break; 
} 

я имею эту ошибку на этой линии: case PreEtat.IND:

Ошибка:

Type mismatch: cannot convert from BigDecimal to int 
+0

Переключатель случае заявления со значениями десятичные кажется плохой идеей. Вы предпочитаете использовать перечисления? –

+0

@ArnaudDenoyelle есть пример – Mercer

ответ

0

По documentation:

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

case PreEtat.IND в вашем switch относится к BigDecimal постоянной, которая не будет компилировать.

Возможно, вы хотите инициализировать и протестировать константу int, вызвав intValue на примере BigDecimal.

Стоит отметить, что вы теряете десятичную часть своего номера, что делает условный тест в вашем switch немного странным.

2

Вы можете попробовать использовать BigDecimal.intValue():

Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of this BigDecimal value as well as return a result with the opposite sign.

Смежные вопросы