Search code examples
delphipascallazarus

How to format a number in scientific notation


So basically I have this function which returns: 3.00000000000E000

function lang():extended;
begin
wynik := 0 ;
   counter := 1;
   temp :=1;
   input := 2;


   for i:= 1 to 4 do
       begin
       for k:= 1 to 4 do
       begin
       if i = k then counter := counter
       else temp := temp * ((input - a[k]) / (a[i] - a[k]));



       end;
       wynik := wynik + temp*f[i];

       temp := 1;
      end;
      Result := wynik;

end;            

But when I try to print it on the application screen using FloatToStr, I get only 3.

procedure TFormCalculator.Button1Click(Sender: TObject);
begin
     Edit1.Text := FloatToStr(lang());
end;

How can I keep the long version of the result ?


Solution

  • You have to understand that computers do not store numbers as strings of characters (text). In this case, you are working with floating-point numbers. Please read that Wikipedia article. (Integers are much simpler.)

    Then, every time a number is displayed on-screen, a computer subroutine creates a string of characters (text) out of that number.

    So you always have the same number, but different systems create different textual representations from it.

    FloatToStr will use a simple default number format. You want to use a particular format (called "scientific" or "exponential") with 12 digits. So you need to use a float-to-string routine that supports that:

    Format('%.12e', [3.0], TFormatSettings.Invariant)
    
    FormatFloat('0.00000000000E+000', 3.0, TFormatSettings.Invariant)
    
    FloatToStrF(3.0, ffExponent, 12, 3, TFormatSettings.Invariant)
    

    Please read the documentation for each function: