I learnt something rather intriguing today on the old Force.com platform: decimals just don’t behave how I expected them to when converting them to strings. I have obviously set myself up with that line but nevertheless let me go through the motions.

Before today I would have expected the following code to display the same three strings on each of the lines.

That is, despite how I declared the decimal in code, they would all be stored the same and hence all output the same way – truncated to zero decimal places in this case, given they are all exactly one. However when I run the page I get the following result:

Output 1

This struck me as a bit odd as it’s actually remembering how I declared the number and then using that when it converts it back to a string.

This got me thinking a little bit: is there some weird bug where by the numbers are considered to be different? I didn’t think this was the case but you can never be too sure so I added the following two methods to my test class and got the following output on the page:

Output 2

As expected comparing the numbers they are the same; they are both exactly 1. However comparing the strings we see that they are different (I know we could see that from the previous output but it’s always good to see what the compiler thinks).

My next thought was what does it do when we add decimals together that have been declared with a different precision? This leads to the following tests:

Output 3

We can see from this that order of inputs doesn’t matter and that the result will always have the precision of the most precise input.

So now that we know how it all works, even if it wasn’t what I originally thought, but where does that get us? Well strangely enough I had an application for this pretty much straight after I discovered it. I had to send a JSON object to a ReST service and needed to make sure that all the numbers I sent were formatted to show two decimal places. This little oddity means that I can simply multiple my input by 1.00 and I know that when I take the string value of the result I will have everything formatted just the way I want it. Perfect.

Output 4

Update

It has been rightly pointed out to me that this phenomenon is expected and well documented behaviour (SF Docs) Thanks gain @jamesmelv before I write my next post I will promise to read the documentation.