Rounding


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Rounding

  1. #1
    Join Date
    Nov 2004
    Posts
    14

    Rounding

    How can you get decimal places to be rounded up? Like for instance if you had 3.125 and you wanted it to be output as 3.13.

  2. #2
    Join Date
    Sep 2004
    Posts
    150
    public double roundMe(int positionRoundingTo, double original)


    // I could do this for you but I would feel guilty if it was your homework.

    // Therefore I'll do it by example:

    // you seem to be wanting to go to two decimal places

    roundMe(2, 3.125);

    double multiplier = 10.0 ^ (positionRoundingTo)

    ie 100.0 = 10 ^ 2;

    (since you want two decimal points)

    3.125 * multiplier = 312.5

    (3.125 * 100.0 = 312.5)


    The trick with rounding is to add (0.5) once you have the decimal in the right spot.

    312.5 + 0.5 = 313.0

    then you keep just the integer portion of 313.0, resulting in 313.


    you then make 313 back into a double.

    313.0

    then you divide it by that multiplier number determined above.
    313.0/100.0 = 3.13

    and return it as your answer:
    3.13

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center