Friday 24 September 2010

Converting decimal value to integer (don't fall into the trap!!)

During data handling within an application, it is not unusual to have a requirement to convert a decimal value into an integer equivalent. When attempting to do accomplish this inside Apex code, you may think that writing something similar to the following will perform the conversion:

Decimal decimalValue = 12.0;
Integer integerValue = Integer.valueOf(decimalValue);

Using code like this will compile without a problem, but upon execution, an error message "System.TypeException: Invalid Integer" will appear (see screen-shot for an example). This is because the input variable "decimalValue" contains more than just numbers, it also contains a decimal place, which causes the conversion to be rejected by the "valueOf" function.


The method that should always be used to perform this kind of conversion is *decimal variable*.intValue(). So in our example above the Apex code should look like this:

Decimal decimalValue = 12.0;
Integer integerValue = decimalValue.intValue();


Now the conversion will work without error.