Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1349
  • Last Modified:

Delphi - Str function: Double type with 12 decimals results in wrong string

I'm using the Str function in Delphi 6 (to be able to ignore locale differences and make sure the decimal separator is always period) and when I have a Double type variable and set the Decimals indicator to 12, I can get strange results. If the Double type variable holds the value 270000 (Frac = 0), the call to Str results in a string like '270000.000000000032', i.e. it for some reason adds some decimals to the very end. Can this be a problem with floating point accuracy or something similar, and what would be a good solution to this? However, this seems to be tied to perhaps something else that has been done with the variable, since when I try to create a reduced code like the one attached, this error does not occur. In my actual code the ActVal comes from other variables and has had a life of its own before, so something in there is probably causing this, but the end result still is, that the debugger shows the value as 270000 without decimals and even a (Frac(ActVal) = 0) test evaluates to true, and still the resulting S ends with 32.
  S: string;
  ActVal : Double;
    ActVal := 270000;

Open in new window

  • 2
1 Solution
You can use:

S := FormatFloat('0.000000000000',ActVal);

This function was always working fine for me
Sorry my mistake. FormatFloat will use separator defined in DecimalSeparator variable. To ensure it will be periond, using FormatFloat you have to use StringReplace too:

s := StringReplace(FormatFloat('0.000000000000',ActVal),DecimalSeparator,'.',[rfReplaceAll]);
FALECoderAuthor Commented:
Thanks dprochownik, I guess that could be a good way to fix this. I haven't yet tried if it works in my situation (I made a more crude solution that works also in my case and don't have time just now to try this also, but I'll keep this in mind), but I would think it should work ok.

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now