Float is changing the actual value

Tip / Sign in to post questions, reply, level up, and achieve exciting badges. Know more

cross mob
CeGu_1509311
Level 2
Level 2
First like received

Hi, 

   

I'm trying to get first decimal from a float, however when I'm debigging the aplication it changes the actual value for exmaple:

   

float test = 5.1;

   

 

   

The debugger says that the value stored is 5.0999999, the same issue is happenning with 

   

float test = 5.100001;

   

debugger says that test = 5.100004.

   

 

   

With this issue I can't get the fist decimal.

   

 

   

Any idea??

0 Likes
1 Solution
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

The difference you see has to do with the representation of floats as digital numbers, you will always get divergences between decimal and float representations.

   

What exactly do you need the first decimal for? When you want to display that number use sprintf()

   

You even may use

   

HelpInt = (int)(fabs(MyFloat) * 10.0);

   

Help2Int = HelpInt / 10;

   

Help2Int *= 10;

   

FirstDec = HelpInt - Help2Int;

   

 

   

Another way could be to add 0.05 to force rounding

   

See a discussion about round() here.

   

 

   

Happy coding

   

Bob

View solution in original post

0 Likes
1 Reply
Bob_Marlowe
Level 10
Level 10
First like given 50 questions asked 10 questions asked

The difference you see has to do with the representation of floats as digital numbers, you will always get divergences between decimal and float representations.

   

What exactly do you need the first decimal for? When you want to display that number use sprintf()

   

You even may use

   

HelpInt = (int)(fabs(MyFloat) * 10.0);

   

Help2Int = HelpInt / 10;

   

Help2Int *= 10;

   

FirstDec = HelpInt - Help2Int;

   

 

   

Another way could be to add 0.05 to force rounding

   

See a discussion about round() here.

   

 

   

Happy coding

   

Bob

0 Likes