Search code examples
delphiformatfloating-point-conversion

Delphi FormatFloat


I have an output txtfile with some float numbers and I like to print in different formats, y try with:

FormatFloat('00000;000.0;00.00', val)  
FormatFloat('00.00;000.0;00000', val)  

But I take wrong outputs. What I need is:

  • If val < 10 then output like '00.00'
  • If 10 < val < 100 then output like '000.0'
  • If val > 100 then output like '00000'

It's a huge amount of float values, so, I need a low processing solution and I think more conditionals will slow down the application. ¿Any advice?

Thank you


Solution

  • Using conditional tests to sort the values into separate outputs is not going to affect performance in a significant way. The format process is far more elaborate. One important thing about optimization is to only walk that path if you can measure a performance hit in the actual code.

    if (val < 10) then
      s := FormatFloat('00.00',val)
    else
    if (val < 100) then
      s := FormatFloat('000.0',val)
    else
      s := FormatFloat('00000',val);
    

    Also consider using the thread-safe FormatFloat with a supplied FormatSettings variable.