0

I am trying to format float numbers in RAD Studio C++ Builder, but for some reason when I multiply a whole number with a number like 0.01 for example, the result gives about 15 decimal points. I tried RoundTo() and SimpleRoundTo() but nothing works. This is the codes I use:

String value = EditNickel->Text;
float numVal = StrToFloat(value) * 0.05;
ListBoxNickel->Items->Add(numVal);

Example: If I input value as 1, the result would give 0.0500000007450581.

Sal So
  • 15
  • 5
  • 3
    That's simply the best that `float` can do, see https://www.h-schmidt.net/FloatConverter/IEEE754.html, it can only store `0.04999999701976776123046875` or `0.0500000007450580596923828125`, `0.05` is not representable as a `float` – Alan Birtles Apr 11 '22 at 20:07
  • 3
    Tactical note: Because what you've stumbled over here can lead to interesting mistakes handling money and people take their money very, VERY seriously, never process money in floating point. Compute it all in integers with the smallest denomination as the basic unit. In US dollars, that would be do all of the math in cents. When you need to show dollar amounts, you very carefully format the display to be precise with no rounding, truncation or other artefacts. – user4581301 Apr 11 '22 at 20:29
  • Thanks so much for the help. I will try working with integers instead. – Sal So Apr 11 '22 at 21:04

0 Answers0