6

I have a decimal variable and i am setting the value of the decimal by using a formula

Decimal test=0;
test = (a.Date_of_First_Order__c.daysBetween(lastDateForMonthOfRating) /(365*12));
//assuming the days between returns 30
// test should hold 0.0068493
system.debug(test); // But it holds 0
test.setscale(4);
 system.debug(test); // But it still holds 0

Is there any way to get the whole value?

9

You're dividing an integer by an integer, so you're ending up with an integer.

Change the calculation to this:

test = (a.Date_of_First_Order__c.daysBetween(lastDateForMonthOfRating) /(365 * 12.0));

The type of an expressions is determined by the types of the operands, and an operand can be converted to a more precise type if needed. Theses are called arithmetic conversions. I can't find the details for Apex in particular right now but this MSDN article explains it.

There is some discussion in the developer guide regarding numeric types, but it doesn't talk in detail about the promotion rules used:

Additional Considerations for Data Types Data Types of Numeric Values Numeric values represent Integer values unless they are appended with L for a Long or with .0 for a Double or Decimal. For example, the expression Long d = 123; declares a Long variable named d and assigns it to an Integer numeric value (123), which is implicitly converted to a Long. The Integer value on the right hand side is within the range for Integers and the assignment succeeds. However, if the numeric value on the right hand side exceeds the maximum value for an Integer, you get a compilation error. In this case, the solution is to append L to the numeric value so that it represents a Long value which has a wider range, as shown in this example: Long d = 2147483648L;.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.