Trimming a decimal with coldfusion & regex
January 12th, 2012
Today I had to import lots of measurements into a mySql table. The columns allow 3 places after the decimal. The data has mixed precision – some values use all 3 places, others use none. To make the output look clean I didn’t want to show all 3 places all the time. So numberFormat() was out. And unlike PHP, coldFusion’s trim() function does not take any parameters (trim trailing zeros and periods). I came up with using two regular expressions to remove any trailing zeros, then the trailing period if any.
Here is some example data:
- 6.000
- 0.375
- 0.500
When using numberFormat(), the output is:
- 6
- 0
- 1
… and numberFormat(val, 0.000) gives:
- 6.000
- 0.375
- 0.500
Blech. So here’s the function that gave exactly what I wanted:
<cffunction name="trimDecimal"> <cfargument name="value"> <cfreturn REReplace(REReplace(value, "0+$", "", "ALL"), "\.+$", "")> </cffunction>
… trimDecimal(val) resulting in…
- 6
- 0.375
- 0.5
Perfect.
Recent Comments