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?
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.
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.
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 CurrToStr
and AsCurrency
, as they automatically uses two digits after the decimal point.
function MyFormatFloat(V: Double): String;
const
DesiredMinPrec = '0.000000000000000';
AssumedMaxPrec = '0.#####';
begin
Result := FormatFloat(DesiredMinPrec, StrToFloat(FormatFloat(AssumedMaxPrec, V)));
end;
精彩评论