Watch, Follow, &
Connect with Us

For forums, blogs and more please visit our
Developer Tools Community.


Welcome, Guest
Guest Settings
Help

Thread: Subtracting doubles



Permlink Replies: 1 - Last Post: Jan 28, 2016 10:32 AM Last Post By: John Murray
Doug Hay

Posts: 122
Registered: 5/26/05
Subtracting doubles
Click to report abuse...   Click to reply to this thread Reply
  Posted: Jan 28, 2016 9:46 AM
I have this code

double Difference = CurrentRaceTime - LastTime;

CurrentRaceTime = 309.606

LastTime = 302.8

Difference = 6.8059999999999998 (this is close to the value, I may have the wrong # of '9's)

How can I get this to be the correct value of 6.806?

C++ Builder XE10
John Murray

Posts: 12
Registered: 1/22/16
Re: Subtracting doubles
Click to report abuse...   Click to reply to this thread Reply
  Posted: Jan 28, 2016 10:30 AM   in response to: Doug Hay in response to: Doug Hay
Doug Hay wrote:
I have this code

double Difference = CurrentRaceTime - LastTime;

CurrentRaceTime = 309.606

LastTime = 302.8

Difference = 6.8059999999999998 (this is close to the value, I may have the wrong # of '9's)

How can I get this to be the correct value of 6.806?

C++ Builder XE10

If you mean the actual value in the program, you can't due to the specification of IEEE-754 ( https://en.wikipedia.org/wiki/IEEE_floating_point ). Basically, it's impossible to represent that specific number in base2.

If you mean when you display it to the user, you can use FloatToStrF ( http://docwiki.embarcadero.com/Libraries/Seattle/en/System.SysUtils.FloatToStrF ) to display the value to a given decimal place.

e.g.
Label1->Caption = FloatToStrF(Difference , ffNumber, 16, 3);
Legend
Helpful Answer (5 pts)
Correct Answer (10 pts)

Server Response from: ETNAJIVE02