-
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);
}
-
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
-
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.
-
Hey thanks guys both methods are great! Really appreciate your help.
-
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