Wednesday, March 22, 2006

StrToDateDef, RoundTo and BoolToStr

Delphi has 2 functions not present in FPC:
function StrToDateDef(const S: string; const Default: TDateTime): TDateTime;
function RoundTo(const AValue: Double; const ADigit: TRoundToRange): Double;

The first one tries to convert String to TDateTime, and if the conversion fails, the result is the value informed at the Default parameter. The second one does banker's rounding to a given precision, informed in power of ten. To round to cents, you need to pass -2, as 10 ^ -2 is 1/100.

There's another function that is present but has different behaviour. It's BoolToStr:
//--- Delphi's BoolToStr
function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string;
If UseBoolStrs is false (the default), it returns '-1' for true and
'0' for false. If UseBoolStrs is true, it returns the strings 'TRUE'
and 'FALSE'. In Free Pascal it's like this:

//--- in objpas/sysutils/sysstr.inc
function BoolToStr(B: Boolean): string;
begin
If B then
Result:='TRUE'
else
Result:='FALSE';
end;

So a call to BoolStr(true) would return '-1' in Delphi and 'TRUE' in FPC. I don't know if it was pointed before, and I agree that returning 'TRUE' makes a lot of sense, but when porting an application this may lead to trouble. A simple "fix" would be add an extra boolean parameter, with the default value of true:
//--- in objpas/sysutils/sysstr.inc
function BoolToStr(B: Boolean; TF: Boolean = true): string;
begin
If TF then
begin
If B then
Result:='TRUE'
else
Result:='FALSE';
end
else
begin
If B then
Result:='-1'
else
Result:='0';
end;
end;

Of course, some may oppose to this change, as it would be a hack made just in order to keep Delphi compatibility.

No comments: