views:

253

answers:

3

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)?

+2  A: 

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

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

Alex T.
I worked it out, dwoz, thanks!(For anyone else looking, you replace 'FloatToStr(SavedValue[1]);' with 'Format('%n', [SavedValue[1]]);'
Chris55
+4  A: 

you can use the FormatFloat Function

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

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.

skamradt
Personally, I would store the user input "as-is" and then work from that when needed. Thus store the text and convert only when necessary. That way you won't suffer this issue.
mj2008
@mj2008, the issue is as you perform calculations your not calculating against what you think you have, but an approximation.
skamradt