Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easier way to do boolean conversions?

Tags:

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.

like image 730
Jerry Dodge Avatar asked Nov 06 '12 00:11

Jerry Dodge


People also ask

What are different ways to convert any value to a boolean?

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”.

How do you convert a value to a boolean?

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.

How do you convert boolean to true or false?

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 .


2 Answers

In the unit StrUtils, there is ifthen()

StrVal := IfThen(BoolVal,'True','False'); 

And for this specific case you could even use:

StrVal := BoolToStr(BoolVal); 
like image 181
Wouter van Nifterick Avatar answered Sep 21 '22 17:09

Wouter van Nifterick


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'); 
like image 45
Marjan Venema Avatar answered Sep 21 '22 17:09

Marjan Venema