SysUtils defines the well-known IntToStr and FloatToStr, which return a Unicode String - but not an AnsiString. If you want to use AnsiStrings in your application, you may want to use versions of these routines that return an AnsiString. Since these didn’t exist, yet, I’ve written a set of routines to help us converting integers and floats to AnsiStrings, based on the built-in Str function.

unitConvert;interfaceIntToAnsiStr(X: Integer; Width: Integer = 0): AnsiString;

functionfunctionFloatToAnsiStr(X: Extended; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;overload;functionFloatToAnsiStr(X: Double; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;overload;functionFloatToAnsiStr(X: Single; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;overload;implementationIntToAnsiStr(X: Integer; Width: Integer = 0): AnsiString;

functionbegin

Str(X: Width, Result);end;functionFloatToAnsiStr(X: Extended; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;begin

Str(X: Width: Decimals, Result);end;functionFloatToAnsiStr(X: Double; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;begin

Str(X: Width: Decimals, Result);end;functionFloatToAnsiStr(X: Single; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;begin

Str(X: Width: Decimals, Result);end;end.

Note that the overloaded FloatToAnsiStr function uses default Width and Decimal arguments (with a default value of 0). Also note that the Str function always uses the dot as decimal separator in the string result, and doesn’t consider the DecimalSeparator value. If you want to use the DecimalSeparator, you may want to change the functions as follows:

functionFloatToAnsiStr(X: Double; Width: Integer = 0;

Decimals: Integer = 0): AnsiString;const

Dot: AnsiChar = '.';begin

Str(X: Width: Decimals, Result);

ifDecimalSeparator <> '.'then

begin

Decimals := AnsiPos(Dot, Result);

ifDecimals > 0thenResult[Decimals] := AnsiChar(DecimalSeparator)

end;

end

This will use the DecimalSeparator, narrowed back to AnsiChar (and I’m assuming nobody will use a Unicode Character which doesn’t “map” back to an AnsiChar as DecimalSeparator, but if you do, you could just stick to the normal FloatToStr anyway).

This tip is the 8th in a series of Unicode tips taken from my Delphi 2009 Development Essentials book published earlier this week on Lulu.com.

## No comments:

Post a Comment