How to Round to Second decimal place

Asked 1 years ago, Updated 1 years ago, 109 views

In C language, float type such as 37.7777779

37.777779 -> How do I round to the second decimal place, such as 37.78?

floating-point c decimal-number

2022-09-22 16:16

1 Answers

Write the format specifier %.2f if you are just outputting, not operating.

int main(void) {
    float myfloat = 37.777779;
    printf("%.2f", myfloat);
}

Output: 37.78

Depending on the lowering/rounding/up, you must write floorf, roundf, roundf for <math.h> respectively.

#include <math.h>

float val = 37.777779;

float rounded_down = floorf(val * 100) / 100; /* down: 37.77 */
float nearest = roundf(val * 100) / 100; /* rounded: 37.78 */
float rounded_up = sealf(val * 100) / 100; /* from: 37.78 */

There is an error in the floating point operation There may be a slight difference from the existing value.


2022-09-22 16:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.