Is there an easier way to do boolean conversions?

Jerry Dodge picture Jerry Dodge · Nov 6, 2012 · Viewed 29.3k times · Source

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.

Answer

Wouter van Nifterick picture Wouter van Nifterick · Nov 6, 2012

In the unit StrUtils, there is ifthen()

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

And for this specific case you could even use:

StrVal := BoolToStr(BoolVal);