I have used this scenario many times in nearly all my projects, when I'm doing some sort of data conversion, when it comes to booleans, I kinda get a little lost when it comes to making it simple. This statement below sticks out like a sore thumb all over my code:
if BoolVal then StrVal:= 'True' else StrVal:= 'False';
I'm wondering if there's an easier way to perform this evaluation? Perhaps some use of the Case
statement I don't know about? My actual implementation is more complex than just StrVal
but it does consist of returning two different values depending on whether it's True or False. For example, here's some real code...
if fsBold in Can.Font.Style then ConvertTo(AddSomeOtherText + 'True') else ConvertTo(AddSomeOtherText + 'False');
That's just to emphasize on how simple I'm hoping. I'm wondering if I can do something along the lines of this:
ConvertTo(AddSomeOtherText + BoolToStrCase((fsBold in Can.Font.Style), 'True', 'False'));
I'm sure that's not a real command, but I'm looking for that type of simplicity in one single line.
We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.
The Boolean() Function Boolean() is a global function that converts the value it's passed into a boolean. You shouldn't use this with the new keyword ( new Boolean ) as this creates an instance of a Boolean that has a type of object. Below is an example of the correct use of this function.
You can convert True and False to strings 'True' and 'False' with str() . Non-empty strings are considered True , so if you convert False to strings with str() and then back to bool type with bool() , it will be True .
In the unit StrUtils
, there is ifthen()
StrVal := IfThen(BoolVal,'True','False');
And for this specific case you could even use:
StrVal := BoolToStr(BoolVal);
Ow com'on nobody ever heard of an array indexed by boolean?
const BOOL_TEXT: array[boolean] of string = ('False', 'True'); YES_NO_TEXT: array[boolean] of string = ('No', 'Yes'); ERROR_OR_WARNING_TEXT: array[boolean] of string = ('Warning', 'Error');
It is in fact what BoolToStr itself uses!
function BoolToStr(B: Boolean; UseBoolStrs: Boolean = False): string; const cSimpleBoolStrs: array [boolean] of String = ('0', '-1');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With