Tuesday, October 16, 2012

Salesforce Save error: Illegal assignment from Decimal to Long

A very simple type conversion error occurs in Apex when trying to implicitly cast from a Decimal (an arbitrary precision number) to a Long (A 64-bit number that does not include a decimal point).

Save error: Illegal assignment from Decimal to Long

I noticed some inherited code was solving the issue by converting via an intermediate String. Using the dedicated Decimal.longValue() was a bit cleaner.

Decimal testDecimal = 123.0;
Long convertedDecimal = testDecimal; // results in "Illegal assignment from Decimal to Long"

// Conversion via a string works, but is a bit ugly
Long conversionViaString = Long.valueOf(String.valueof(testDecimal));
System.assertEquals(123, conversionViaString);

// Direct conversion using dedicated Decimal method
Long directLongConversion = testDecimal.longValue();
System.assertEquals(123, directLongConversion );