chendriksen
chendriksen

Reputation: 1024

Reducing decimal places in Delphi

I am storing a list of numbers (as Double) in a text file, then reading them out again.

When I read them out of the text file however, the numbers are placed into the text box as 1.59993499 for example, instead of 1.6.

  AssignFile(Pipe, 'EconomicData.data');
  Reset(Pipe);
  For i := 1 to 15
    Do ReadLn(Pipe, SavedValue[i]);
  CloseFile(Pipe);
  Edit1.Text := FloatToStr(SavedValue[1]);

The text in Edit1.text, from the code above, would be 1.59999... instead of the 1.6 in the text file. How can i make it so the text box displays the original value (1.6)?

Upvotes: 0

Views: 8379

Answers (3)

skamradt
skamradt

Reputation: 15548

Just be careful when using floating points. If your going to be performing calculations using the values, then your better off using either a currency type or an integer and implying the decimal point prior to saving. As you have noticed, floating point values are approximations, and rounding errors are bound to eventually occur.

For instance, lets say you want to store tenths in your program (the 1.6), just create an integer variable and for all intensive purposes think of it as tenths. When you go to display the value, then use the following:

Format('%n',[SavedValue[1]/10]);

Currency is an integer type with an implied decimal of thousandths.

Upvotes: 1

Alexander Frost
Alexander Frost

Reputation: 643

Sorry, I wasn't sure whether it will suit your requirements, but my original answer was to use:

Format('%n', [SavedValue[1]]);

Upvotes: 2

RRUZ
RRUZ

Reputation: 136441

you can use the FormatFloat Function

var
  d: double;
begin
d:=1.59993499 ;
Edit1.Text:=FormatFloat('0.0',d); //show 1.6
end;

Upvotes: 4

Related Questions