Thread: Rounding help

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    3

    Rounding help

    Hey can someone help explain how to use the rounding function.

    I want to round to the 2nd digit in a float. Such as 1.85458 to 1.85. How would i go about doing this. I currently keep rounding to the closest integer so the above would round to 2. Thank you in advance for your help!

    Code:
    #include <stdio.h>
    #include <math.h>
    
    
    int main(void)
    {
        float n;
        do
        {
        printf("input a floated number to 7th decimal: ");
        n = ask for integer;
        }
        while (n != 0);
        
        n = roundf(n);
        
        printf("%.7f\n", n);
    }

  2. #2
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Multiply by 100
    1.85458 x 100 = 185.458

    Then round to nearest integer using method you said you had -> 185
    Then divide by 100 -> 1.85

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    That's what round does, round to the nearest integer. If that's not what you want to do, then don't use round(n).

    You might consider this, though: if you have a price of 1.85458, then that price to the nearest cent (or whatever your local equivalent name) is 1.85. So you might convert to cents (express that as an operation), then you can use round on that number (and then convert it back).

    Note also that you'll need to do this conversion inside the loop, not after it.

  4. #4
    Registered User
    Join Date
    Jan 2014
    Posts
    3
    Hey thanks guys both methods are great! Really appreciate your help.

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    It should also be mentioned that if all you want is to print the number rounded to 2 digits after the decimal point, just use a precision of 2 in the format specifier:
    Code:
    printf("%.2", 1.457);   // prints 1.46
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rounding up or down accordingly...
    By ktran03 in forum C Programming
    Replies: 9
    Last Post: 10-20-2008, 06:20 AM
  2. Help with rounding INT's
    By iAmFedor in forum C++ Programming
    Replies: 2
    Last Post: 05-19-2008, 04:03 PM
  3. Rounding
    By mdoland in forum C# Programming
    Replies: 2
    Last Post: 10-04-2007, 01:18 AM
  4. rounding
    By limitmaster in forum C++ Programming
    Replies: 8
    Last Post: 06-24-2006, 11:00 PM
  5. C++ rounding
    By dogbert234 in forum C++ Programming
    Replies: 9
    Last Post: 12-23-2005, 04:09 PM