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.

5 comments:

  1. As a developer.. I find wee snippets like this constantly useful, as super-fast reference for those easily forgotten nuances. Cheers Christopher Alun.

    ReplyDelete
  2. Just solved a problem I've had for past hour! Thanks!

    ReplyDelete
  3. She shares the family's story with students at area high schools. She shows pictures of the men when they were children and teenagers and on Redington Beach playing football hours before they died. She recalls McConnell's Facebook post from that day an announcement that their vacation was the best idea he'd had in years..

    This woman had also tried to commit suicide. Ray Ban Outlet In a statement to the court she said: have no relationships with anyone. I felt very dirty as a woman. Take action. Don't procrastinate. All Cheap Michael Kors Handbags the planning in Nike Air Force 1 Cheap Outlet the world will not help you achieve your goals.

    The report, Jordan Shoes For Sale released Wednesday at the CES MK Outlet Online 2015 Consumer Electronics Show in Las Vegas, finds Americans look at their mobile phones an average of 100 times each day. We're addicted and either Best Yeezys don't know or care how much damage phone time may be doing to our eyes, not to mention our relationships and Coach Outlet Clearance Sale psyche. Digital addiction, or "nomophobia" the fear of being without your mobile device Coach Outlet Online is even contributing to physical health problems like chronic back pain...

    ReplyDelete