spspli
spspli

Reputation: 3338

AsFloat convert to string

Hi I want to convert "qrysth.Fields[i].AsFloat" to a string so I use the following code: FormatFloat('0.###############',qrysth.Fields[i].AsFloat)

but I find the result string is 12.000000000000001 while qrysth.Fields[i].AsFloat is 12.00. I know FormatFloat actually not use 12.00 to do the convert, but use an infinite number of binary to do the convert. (like 0.1 in decimal system is 0.1, but it is an infinite number in binary system 0.00011001100...)

Is there other way I could get 12.00 in the case above? or 12.000000000000000 at least?

Upvotes: 0

Views: 2649

Answers (4)

NGLN
NGLN

Reputation: 43649

function MyFormatFloat(V: Double): String;
const
  DesiredMinPrec = '0.000000000000000';
  AssumedMaxPrec = '0.#####';
begin
  Result := FormatFloat(DesiredMinPrec, StrToFloat(FormatFloat(AssumedMaxPrec, V)));
end;

Upvotes: 0

Ken White
Ken White

Reputation: 125689

I want to convert "qrysth.Fields[i].AsFloat" to a string

Then why not use AsString?

qrysth.Fields[i].AsString

This will give you the best representation, as long as you're not concerned about the exact width. If you are, use FormatFloat with the exact number of digits you need - in other words, if you're looking for 12.00, use FormatFloat('##.##', qrysth.Fields[i].AsFloat), or even better CurrToStrand AsCurrency, as they automatically uses two digits after the decimal point.

Upvotes: 1

Rob Kennedy
Rob Kennedy

Reputation: 163277

If you really get 12.000000000000001, then your field didn't hold exactly 12, so the output is correct. You asked for high precision by putting so many # characters in the format. If you don't want it so precise, then use a less precise format string.

Upvotes: 5

Sertac Akyuz
Sertac Akyuz

Reputation: 54802

FormatFloat('0.00',qrysth.Fields[i].AsFloat) will give '12.00'.

To be able to get '12.000000000000000' you should do the rounding yourself, as there's no loss of precision.

Upvotes: 2

Related Questions