Sep 21, 2016

Roundoff Double/Float values to any decimal points

            While working with android apps many of the time the requirement comes up were we need to round off the decimal values to a specific decimal points. Well thats not a big deal and as u migth have been thinking there should be just some simple method that we can call to round off our values directly to the required format.



            But the thing is rounding off this double values is not hard its justa little tricky. It had surely wasted almost my day finding the easiest method to do it but finally i had to end my search with some simple mathmatical calculation.



Lets take a Example :

I want to Round Off : 1673.342947 into 3 decimal points what i can do for this is :-

1. Store the No in a variable :

        double no = 1673.342947;

2. Multiply it with the required power of 10. If u want to round off to 2 decimal point multiple with 100, for 3 decimal points use 1000 , for 4 decimal points i know u got it!

        no = no * 1000;     //for 3 decimal points

3. Use Math.round function to round this new number. Basically yes it can round the number but it will remove all of the decimal points.

       double roundedNo = Math.round(no);

4. Dont you all think we increased the value of our no by multiplying it with 1000? Now its time to take it back! Divide it with exact same no!!

       roundedNO = roundedNO/1000;

5. Now thats the required Rounded No.

So lets see how it actually works :-

   double no = 1673.342947;                             //no = 1673.342947

   no = no * 1000;                                              //no =  1673342.947
   double roundedNo = Math.round(no);       //roundedNo = 1673343

   roundedNO = roundedNO/1000;                //roundedNo = 1673.343

Does this code looks long? We can compress it to :

double no = Math.round(no * 1000)/1000;

Pretty simple and sweet isnt it!

No comments :

Post a Comment