Converting Numbers to Text

Over the summer I worked on a real estate project. Some of the Salesforce data is used to generate documents and some of those documents need to have numbers spelled out. For example, 1,535,000 would be spelled out as one million five hundred thirty-five thousand.

I didn’t like the solutions I found online so I spent a little time coding my own. It’s not a common use case but I wanted to post my solution in case others find it useful.

If you’re interested in my approach, read on. If you just want the code, it’s on GitHub.

I took the approach of converting the number to a string and then breaking the string into sets of three or less. Wherever you would put a comma to make a large number more readable is a set boundary. For example, 1,535,000 would be three sets.

1 | 535 | 000

I convert each set to text which is pretty straightforward with a number that is three digits or less. Based on the length of the string I add the word billion, million or thousand after it, if necessary. Then I repeat for the next set until all sets are converted.

Because there are so many possible values it’s not practical to test them all. But after testing a few thousand values I think I have a solution that covers every integer value from -2,147,486,647 to 2,147,486,647 correctly. I didn’t need to handle negative values for the real estate project but it’s easy to do and I wanted this to be generic enough that others can use it.

Leave a Comment