Author: Dmitri Papichev
How I convert boolean values to the words depending on the situation? For example,
TRUE here means "Enabled", and FALSE there means "Failed"?
Answer:
Solve 1:
Here is the code snippet to do the job. If the second parameter is omitted, the
function returns "TRUE" or "FALSE".
Modify the function declaration to change the default returning values. Expand
TBooleanWordType and BooleanWord definitions to include more specific values if
needed.
1 interface
2 {...}
3 type
4 TBooleanWordType =
5 (bwTrue, bwYes, bwOn, bwEnabled, bwSuccessful, bwOK, bwOne);
6 {...}
7 function BoolToStr(AValue: boolean;
8 ABooleanWordType: TBooleanWordType = bwTrue): string;
9 {...}
10 {=====================================================}
11 implementation
12 {...}
13 const
14 BooleanWord: array[boolean, TBooleanWordType] of string =
15 (
16 ('FALSE', 'No', 'Off', 'Disabled', 'Failed', 'Cancel', '0'),
17 ('TRUE', 'Yes', 'On', 'Enabled', 'Successful', 'OK', '1')
18 );
19
20 {...}
21 {-----------------------------------------------------}
22
23 function BoolToStr(AValue: boolean;
24 ABooleanWordType: TBooleanWordType = bwTrue): string;
25 begin
26 Result := BooleanWord[AValue, ABooleanWordType];
27 end; {--BoolToStr--}
28 {...}
Solve 2:
29 interface
30
31 function BoolToStr(b: boolean; TrueValue: string = '1'; FalseValue: string = '0'):
32 string; overload;
33
34 implementation
35
36 function BoolToStr(b: boolean; TrueValue: string = '1'; FalseValue: string = '0'):
37 string; overload;
38 begin
39 if b then
40 Result := TrueValue
41 else
42 Result := FalseValue,
43 end;
44
45 // example for italian language
46 s := BoolToStr(CheckBox1.Checked, 'Si', 'No');
Add this overloaded Function to the unit.
Solve 3:
47 const
48 arrBooleanValues: array[Boolean] of ShortString = ('False', 'True');
49 var
50 b: Boolean;
51 s: string;
52 begin
53 b := False;
54 s := arrBooleanValues[b]; // 'False'
55 b := True;
56 s := arrBooleanValues[b]; // 'True'
57 end;
|