You can do it like this:
double a;
scanf("%lf", &a);
printf("%.1lf", a);
If you want to round off a double to only N decimal place, you can use %.Nlf instead of %.1lf .
Answer from gsm on Stack OverflowYou can do it like this:
double a;
scanf("%lf", &a);
printf("%.1lf", a);
If you want to round off a double to only N decimal place, you can use %.Nlf instead of %.1lf .
There are a few few ways you can go about this. If you want to go the rounding direction you can use round() to achieve it.
double a;
scanf("%lf", &a);
// Round to one decimal place
double rounded_value = round(a * 10) / 10;
printf("%.1f\n", rounded_value);
You can change out the round() for a few things but using printf("%.1f\n", ) is the key.
I want to round a double to one decimal point. I tried using round() but it doesn’t work the way I need it. I want to round it so 45.892 is 45.9. How would I do this?
Can I create a variable and set it to a specific decimal place? For example "float z to 5 dp" where z would be recorded to 5 dp for the rest of the program
If you just want to round the number for output purposes, then the "%.2f" format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = roundf(val * 100) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
Using %.2f in printf. It only print 2 decimal points.
Example:
printf("%.2f", 37.777779);
Output:
37.77
I have a question when it comes to rounding in C. Does it round up or down at .5? If it does round up, then does that mean that the smallest value of k in the code below can only be 1?
int main()
{
int k = 13;
int i;
for (i = 0; i < 8; i++) {
printf("%d", (k%2));
k >>= 1;
}
printf("%n");
}