6

I have a need to show the boolean value as string and I'm trying to convert boolean to string but its not coming along, here is what I have done so far:

try to convert using String.valueOf but does not work.

tried this:

boolean b = true;
system.debug('boolean to string: ' + string.valueOf(b));

I'm getting the following:

USER_DEBUG [1]|DEBUG|boolean to string: true

But I want that to be in string like this 'true'

I have also tried to concatenate by using single quote

<apex:variable var="sr" value="{!string.valueOf('"' + record.status + '"')}"/>

then got this error:

Error Error: value="{!string.valueOf('"' + record.status + '"')}" EL Expression Unbalanced: ... {!string.valueOf('"' + record.status + '"')} Error Error: EL Expression Unbalanced: ... {!string.valueOf('"' + record.status + '"')}

4
  • 1
    String.valueOf(b) is a string.
    – sfdcfox
    Jun 24, 2016 at 19:59
  • System.assert( ((Object)(String.valueOf(b)) instanceOf String );
    – sfdcfox
    Jun 24, 2016 at 20:00
  • Take a look at this stackoverflow.com/questions/18833054/… OR what @sebastin kessel mentioned!
    – d_k
    Jun 24, 2016 at 20:07
  • You may want to simply explain what the problem is, not try to find a solution to a problem that might not even solve your problem. This is what we've come to call an x-y problem.
    – sfdcfox
    Jun 24, 2016 at 23:55

2 Answers 2

6

If you really want to format it differently than what you get out of String.valueOf, it is probably worth creating a method for it.

public static String wrapSingleQuotes(Boolean input)
{
    return (input == null) ? '' : '\'' + String.valueOf(input) + '\'';
}

Then you can do:

system.debug('boolean to string: ' + wrapSingleQuotes(b));

Same strategy would apply for parens, double quotes, etc.

In VF, you can simply use outputText:

<apex:outputText value="{!'\'' & myBoolean & '\''}" />
1
  • 1+ is there a way to do it on VFP instead of creating an apex method?
    – Nick
    Jun 24, 2016 at 23:10
8

How about

Boolean theBool = true;

String theString = (theBool) ? 'true' : 'false';

It's more verbose but it works.

PS: in the Debug Log you will not see strings in quotes, are you sure that the String.ValueOf method you called before is not already returning a string?

2
  • 2
    FWIW, your solution forgot about one of the three Boolean states: null. Personally, I'd just use the following: String theString = ''+theBool; This is the same as String.valueOf(theBool), won't crash on nulls, and is shorter than other solutions.
    – sfdcfox
    Jun 24, 2016 at 21:40
  • I wouldn't have used my own solution, tbh... I am still a bit surprised the OP says string.ValueOf() didn't work for him. I suspect he either wanted single quotes (which won't automatically be added) or erroneously expected them. Jun 24, 2016 at 21:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .