Why rounding causes for this code?
double myDoubleNum = 19.99;
printf("%.1lf\n", myDoubleNum);
result: 20
But when I print it whith 2 or more digits it solves
double myDoubleNum = 19.99;
printf("%.2lf\n", myDoubleNum);
result: 19.99
Latest edit:
In retrospect, I think what you really want is how to print one decimal digit without rounding involved.
If it is that case, I myself don't think printf can do that as long as you used %f which deals with float number, note the LSB is also part of the very number, it hence makes no sense to get rid of any of them without rounding.
That said, if you really have the need due to any special use case, you may firstly convert it to string, then print however many digits you want:
int main() {
double num = 2.675; // Cannot be represented exactly in binary
int len = snprintf( NULL, 0, "%.3f", num); // %.3f so you get 2.765 instead of 2.76499..8
char *num_string = (char *)malloc( len + 1 ); // + 1 for null terminator
snprintf( num_string, len + 1, "%f", num);
char *decimal_point_pos = strchr(num_string, '.');
int integer_place_plus_dot = decimal_point_pos - num_string + 1;
int decimal_digits_reserved = 1;
printf("%.*s\n", integer_place_plus_dot + decimal_digits_reserved, num_string );
free(num_string);
return 0;
}
Original answer:
For printf("%.1lf\n", myDoubleNum);
, it effectively says display one decimal digit, the value 19.99 is rounded to one decimal place.
For printf("%.2lf\n", myDoubleNum);
, since the number already has exactly two decimal places, there is no further rounding occurs.
Due to inaccurate representation of floating point number, you may notice the rounding rule sometimes seems to be "broken", e.g., the following case prints out 2.67 as the number 2.675 might be stored as something like 2.6749999999999998.
int main() {
double num = 2.675; // Cannot be represented exactly in binary
printf("%.2lf\n", num); // Expecting 2.68 but might not get it
return 0;
}