Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 204
Piotrek Szymański Avatar asked Oct 23 '25 18:10

Piotrek Szymański


1 Answers

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:

  • Format
  • FormatFloat
  • FloatToStrF
like image 52
Andreas Rejbrand Avatar answered Oct 26 '25 11:10

Andreas Rejbrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!