Wednesday 29 August 2012

Integer, Long, Double and Decimal - Apex

To store numeric values in variables, declare your variables with one of the numeric data types: Integer, Long, Double and Decimal.
Integer
A 32-bit number that doesn’t include a decimal point. Integers have a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647.
Long
A 64-bit number that doesn’t include a decimal point. Longs have a minimum value of -263 and a maximum value of 263-1.
Double
A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a maximum value of 263-1.
Decimal
A number that includes a decimal point. Decimal is an arbitrary precision number. Currency fields are automatically assigned the type Decimal.
Execute the following to create variables of each numeric type.
Integer i = 1;
Long l = 2147483648L;
Double d=3.14159;
Decimal dec = 19.23;
You can use the valueOf static method to cast a string to a numeric type. For example, the following creates an Integer from string ‘10’, and then adds 20 to it.
Integer countMe = Integer.valueof('10') + 20;
The Decimal class has a large number of instance methods for interrogating and manipulating the values, including a suite of methods that work with a specified rounding behavior to ensure an appropriate precision is maintained. The scale method returns the number of decimal places, while methods like divide perform a division as well as specify a final scale. Execute the following, noting that the first argument to divide is the number to divide by, and the second is the scale:
Decimal decBefore = 19.23;
Decimal decAfter = decBefore.Divide(100, 3);
System.debug(decAfter);
The value of decAfter will be set to 0.192.

2 comments: