Search code examples
delphistring-formattingfreepascal

How to convert integer whole value to 3 digit dot seperated string


I can't believe I am struggling so much with this! Hopefully it is an easy one. Using either Delphi or Freepascal:

Given the whole integer value "1230", or "1850", how do you format that as a floating point string of 3 digits where the decimal is in the 3rd position, and the trailing digit discarded.

Example

1230 means "v12.3" 1850 means "v18.5"

So I need to convert the first two digits to a string. Then insert a decimal place. Convert the third digit to a string after the decimal place. And discard the zero. I've looked at Format, FormatFloat, Format, and several others, and they all seem to equate to taking existing floating point numbers to strings, or floating point strings to numbers.


Solution

  • Just assign your integer value to a float and divide by 100.0.

    Use Format() or FormatFloat() to convert the value to a string with three digits and a decimal point:

    program Project8;
    
    {$APPTYPE CONSOLE}
    
    uses
      System.SysUtils;
    
    var
      i : Integer;
    const
      myFormat : TFormatSettings = (DecimalSeparator: '.');
    begin
      i := 1230;
      WriteLn(Format('v%4.1f',[i/100.0],myFormat));   // Writes v12.3
      WriteLn(FormatFloat('v##.#',i/100.0,myFormat)); // Writes v12.3
      ReadLn;
    end.