1

I have apex variable in my visualforce page, which is calculated as below -

<apex:variable var="cntFinal" value="{!IF(cntVar1==0,0,(cntVar2+cntVar3)*100/cntVar1)}"/>

Now, I want to set this cntFinal value up to two decimal places. For example, if the value is 0.23769, I want to show 0.24. This conversion have to be as Number, not as a string(using <apex:outputText> will convert it to text). As I will be using this to calculate other values.

5

Keeping everything in visualforce here, there is a function to do precisely what you're looking for, ROUND.

It appears about half-way down the documentation page on visualforce functions

ROUND
Returns the nearest number to a number you specify, constraining the new number by a specified number of digits.
ROUND(number, num_digits) and replace number with the field or expression you want rounded; replace num_digits with the number of decimal places you want to consider when rounding.

An example of usage:

<!-- 20/3 = 6.6666... rounding to 2 decimal places should result in 6.67 -->
<apex:variable var="myVar" value="{!ROUND(20/3, 2)}"/>
|improve this answer|||||
1

Use setScale() method to round a decimal

Decimal no = 1.23345;
Decimal result = no.setScale(2);
system.debug(result);
|improve this answer|||||

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.