+ Start a Discussion
cmarzillicmarzilli 

String Functions?

I am dealing with a lot of different types of fields including number (double and integer), Boolean, DateTime and Date fields.  How can I convert the exact value of these fields into friendly strings?
 
I am looking at the Apex Code Language Reference PDF, but I can't find anything in it.  Is there another more comprehensive Language Reference document some where?
 

This is really strange, say for example I have a variable that is a double named currentValue.  This line of code throws an error:

String test = currentValue;

ERROR:Severity and Description Path Resource Location Creation Time Id
Illegal assignment from Double to String MyTest_Support/Packages myPackage.apex line 22 1171636386867 61

But this line of code does not throw an error:

String test= '' + currentValue;

what am I missing?

zakzak
Its just like java, this works because it'll do an implicit conversion for you
Double a = 1.0;
String b = "" + a;

otherwise you need to use the valueOf method
Double a = 1.0;
String b = String.valueOf(a);

cmarzillicmarzilli
Thanks I guess I need to brush up on my Java, I have been using C# recently. I have my doubles working great now. However I still can't get the bools to work I have tried:
 
String.valueOf(boolean)
String.toString(boolean)
Boolean.valueOf(boolean)
Boolean.toString(boolean)
 
No of these seem to work and the Java docs I found online seem to indicate that either #2 or #4 should work.  Any ideas?
HarryKHarryK
#1 should work.
Try the following:

boolean b = true;
String s = String.valueOf(b);


cmarzillicmarzilli

This is the error I get from Eclipse when I try #1:

 

Severity and Description Path Resource Location Creation Time Id
Method does not exist or incorrect signature: String.valueOf(Boolean) 

MyTest_Support/Packages myPackage.apex line 48 1171978331708 118

cmarzillicmarzilli

Also it seems none of the DateFormat functions that are in Java seem to work.  I get errors on all of these:

   
    String s = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
   
    s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    
    s = DateFormat.getDateInstance(DateFormat.LONG).format(date);
    
    s = DateFormat.getDateInstance(DateFormat.FULL).format(date);
    
    s = DateFormat.getDateInstance().format(date);

I can get the date like this but is this the best method?

    Integer m = date.month();
    Integer d = date.day();
    Integer y = date.year();
    String myDate = '' + m + ' ' + d + ' ' + y;