Move decimal point to where you want to round up, do round up and move it back.
ceil(value * 1000.0) / 1000.0
Answer from MikeCAT on Stack OverflowRounding in C
Decimal places
Rounding offto 2 decimal points - C++ Forum
What is 1.36363 to correct to 3 decimal places
Videos
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");
}
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
So I'm a bit lost as i'm unsure what this would be rounded up. would it be 1.463 or 1.464 maybe? Dumb question I know but thanks!