Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf changing the value while using %.22f

I have a issue with basic typecasting.

#include<stdio.h>

int main()
{
     printf("%.22f",0.30);
     return 1;
}

The output I am getting is 0.2999999999999999888978

Why is 0.3 converted to a lesser value

Any help much appreciated

Nandish

like image 381
Nandish A Avatar asked Aug 20 '26 17:08

Nandish A


1 Answers

This is because 0.30 cannot be exactly represented in binary floating-point. Internally, only an approximation to 0.30 can be stored. Therefore, when you print it all out, you'll get a slightly different number.

http://en.wikipedia.org/wiki/Floating_point

like image 94
Mysticial Avatar answered Aug 22 '26 07:08

Mysticial