Tip: Using Decimal class with Strings in Apex

Today I came across an interesting problem that reminded me of my Java days. A piece of Apex code written by some other developer was broken when I did my fixes.

Here is some background about the broken code. Let's say the file name is “ScaryMovie.cls”

  • It tries to query a Number(18, 0) field from SObject. Let’s say the sobject is Mock__c, and the number field is “Counter__c”.

  • Appends the number field to a string to create a URL, for example:

Mock__c mock = [Select Counter__c from Mock__c where Name = 'Demo'];
String url = 'http://mycooldomain.com/'+ mock.counter__c;
System.debug ('Generated URL :' + url);

The Apex class was an old class, i.e., of 16.0 API version. When executed, with Counter__c value of “1.0”. 

This code generates a URL as shown below: http://mycooldomain.com/1.0

How did things break?

For my fixes, I was using some newer features of Apex and had to upgrade the API version of the class to the latest one. This API version change broke the previously working code!

The URL is now generating as: http://mycooldomain.com/1

Any guess what could be the reason for this showstopper?

Why did this happen?

Update: Thanks to @rich_unger for suggesting the correct cause of the problem. I was previously thinking the problem was because of a change in toString() method implementation from v16.0 to v23.0 of the API. But it's Double class that is used in the v16 API, which has been upgraded to the Decimal class in later versions for more precision.

So, to again get back to the same Double in Apex, we can change the code as shown below:

Mock__c mock = [Select Counter__c from Mock__c where Name = 'Demo'];
Double dblValue = mock.Counter__c .doubleValue();
String url = 'http://mycooldomain.com/'+ dblValue;
System.debug ('Generated URL :' + url);

Ideal practice

Instead of directly appending any queried number field to the String, try storing it as a specific Type(Decimal) in a local variable. This will save you from any accidental code API version upgrade from breaking the existing code.

Your feedback?

Love to hear back.

Abhinav Gupta

First Indian Salesforce MVP, rewarded Eight times in a row, has been blogging about Salesforce, Cloud, AI, & Web3 since 2011. Founded 1st Salesforce Dreamin event in India, called “Jaipur Dev Fest”. A seasoned speaker at Dreamforce, Dreamin events, & local meets. Author of many popular GitHub repos featured in official Salesforce blogs, newsletters, and books.

https://abhinav.fyi
Previous
Previous

Fixed – “Compile Error: Type is not visible: test”

Next
Next

Force.com Developer Console Navigation Trick