Showing posts with label round. Show all posts
Showing posts with label round. Show all posts

Jun 4, 2011

Math.Round Utility in Salesforce

Now rounding your number to desired decimal value is no longer a headache.


How?????


Just use the below method and pass your decimal number as first parameter and the decimal places as second parameter. 
public Decimal roundNumber(Decimal roundNumber , Integer decimalPlace)
    {
        if(roundNumber != null)
        {
            Decimal decPlace = Math.POW(10 , decimalPlace) ;
            return Math.round(roundNumber * decPlace) / decPlace ;
        }
        else
        {
            return 0 ;
        }
    }


Presently salesforce provides Math.Round(your_number) which will return the number after rounding with no decimal values.


For example : If I do this
System.debug('Rounded number : ' + Math.Round(2.333454)) ;


It will return Round Number : 2


I don't find way to get number round with two decimal places like in this case if I want the number to be rounded with two decimal places then it should return 2.33


Above method makes it pretty simple, we only need to pass decimal value and the decimal places in method like this :
Decimal num = roundNumber(1.567 , 2) ;
System.debug('num ::::: ' + num) ;
It will return 1.57


Also another way to round number by decimal places is :
Decimal d = 1.426 ;
Double num = d.setScale(2) ;
System.debug('num ::::::::::::: ' + num) ;


Cheers
Feedbacks are always welcomed