Monday, August 8, 2022

[FIXED] why does the number 51444.325061 doesnot round off to 51444.325 upto 3 decimal places? I want to round off this number in c programming

Issue

#include <stdio.h>
#include <stdlib.h>

int main() {
    float n;
    scanf("%f", &n);
    printf("%.3f", n);
}

input: 51444.325061

my output: 51444.324

expected output: 51444.325

why does I dont get the proper answer?


Solution

32-bit float can encode about 232 different values.

51444.325061is not one of them**. Instead the nearest float is exactly 51444.32421875. The next best choice would be 51444.328125.

Printing 51444.32421875 to 3 decimal places is best as "51444.324".


why does I dont get the proper answer?

float is too imprecise to encode 51444.325061 as OP desires. Using double will help. The same problem exists, yet only appears when about 16+ significant digits are needed.


** Encodable finite values are of the form: some_integer * 2some_exponent.



Answered By - chux - Reinstate Monica
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.