Results 1 to 3 of 3

Thread: Rounding a float to X decimal places

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Mar 2010
    Location
    Heredia, Costa Rica
    Posts
    257
    Thanks
    24
    Thanked 17 Times in 14 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Question Rounding a float to X decimal places

    Hi,

    How can I round a float number like 0.00877193 to 0.01?

    Thanks,
    Carlos.

  2. #2
    Join Date
    Jan 2006
    Location
    Munich, Germany
    Posts
    4,714
    Thanks
    21
    Thanked 418 Times in 411 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows

    Default Re: Rounding a float to X decimal places

    1. multiply by 10 until you have a result > 0,and remember how many iterations you needed (power of10)
    2. multiply your input number by 10 in the power of iterations-1, and use ceil() on the result. (in this case it will give you 1.0)
    3. divide back by 10 in the power of iterations-1.
    ==========================signature=============== ==================
    S.O.L.I.D principles (use them!):
    https://en.wikipedia.org/wiki/SOLID_...iented_design)

    Do you write clean code? - if you are TDD'ing then maybe, if not, your not writing clean code.

  3. #3
    Join Date
    Apr 2010
    Posts
    769
    Thanks
    1
    Thanked 94 Times in 86 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11

    Default Re: Rounding a float to X decimal places

    Or, to use your example's case, add 0.005 and simply truncate at the second decimal place.

Similar Threads

  1. Problems with rounding
    By estanisgeyer in forum Qt Programming
    Replies: 4
    Last Post: 15th December 2009, 23:50
  2. My Network Places in QFileDialog
    By AlHadr in forum Qt Programming
    Replies: 2
    Last Post: 9th November 2009, 15:38
  3. Best places to submit your freeware?
    By tgreaves in forum Installation and Deployment
    Replies: 18
    Last Post: 8th March 2009, 21:20
  4. Replies: 1
    Last Post: 10th February 2009, 09:42
  5. QTableWidget and Decimal places
    By pshah.mumbai in forum Qt Programming
    Replies: 3
    Last Post: 17th August 2008, 08:30

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.