round function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madshov
    New Member
    • Feb 2008
    • 20

    round function

    Hi,

    I need to make a function, that takes as input a double. This should be rounded so it always has a decimal precision of 3:

    12.1234 = 12.123
    12.1235 = 12.124
    12.12 = 12.120
    0 = 0.000

    Is this possible? The output is going to be written to a file, so it's ok to convert the double to a string and let the function return this string, if it makes the problem easier. Does anybody know a nice and clean way to make this function, or do I need to go ugly??
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Why not simply use the format "%.3f" when you print those numbers to the file?

    kind regards,

    Jos

    Comment

    • madshov
      New Member
      • Feb 2008
      • 20

      #3
      But can I make a fixed length. e.g. 8 characters with blankspaces i front:
      " 23.233"

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        "%8.3f"

        but note if the number will not fit in 8 characters the 8 will be ignored for example

        10000.001

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          Also try googling "printf format codes"

          Comment

          • jorba101
            New Member
            • Jun 2008
            • 86

            #6
            If you do "%08.3f" the number will get filled with as many "0" in the front as needed to get it 8 numbers.

            But still you'll have to check for the number not to be bigger than certain value, so that it does not get larger than 8.

            See http://www.acm.uiuc.edu/webmonkeys/b...12.html#printf for further detail
            Last edited by jorba101; Jun 9 '08, 11:54 AM. Reason: Fixing

            Comment

            Working...