Tsallaka zuwa abun ciki
Justice Tech School

Floating Point Numbers

float, double and long double store decimals with limited precision, so 0.1 + 0.2 is not exactly 0.3. Compare with a tolerance and include <math.h> for sqrt, pow, floor and fabs.

Example
double a = 0.1 + 0.2;
printf("%.17f\n", a);
printf("%d\n", fabs(a - 0.3) < 1e-9);
printf("%.2f %.1f %.0f\n", sqrt(2), pow(2, 10), floor(7.9));

Result

0.30000000000000004
1
1.41 1024.0 7

Exercise

Absolute value of a double.

(x)

Quiz Test

Why compare floats with a tolerance?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.