Thursday 12 December 2013

Help me with some code, if you have a moment: numberFormat()

G'day:
Hey, I'm trying to come up with the most expedient way to effect this. I have a number which could be zero or more decimal places. If there are zero decimal places, I just want to display it as an integer. If it has a decimal component, I want to display up to two decimal places, but without any trailing zeros. EG:

ValueDesired rendering
00
0.00
0.000
0.0000
0.0010
0.10.1
0.100.1
0.1000.1
0.1010.1
0.110.11
0.1100.11
0.1110.11

I would have thought this would be easily achievable with just numberFormat(), but it only has a mandatory decimal point, it does not have an optional one. Also "9" does not work as documented: it always displays a digit on the right-hand-side of the decimal point. So numberFormat("1.0", "9.9") returns "1.0", whereas if it's optional, it should return "1" (although the "." being mandatory would cause issues still here, as that would mean I'd get "1.", which helps no-one).

Obviously this is not a tricky problem to solve other ways, with a regex or a coupla separate statements, but I thought I'd pick yer brains in case I'm missing something obvious, or someone can come up with a nice single-expression solution.

I've created a testRig.cfm gist here:

If you fancy it, post yer own gist with your treatment of this inserted where indicated. Wouldn't it be nice if we had a CFMLFiddle type thing?


Thanks for any suggestions!


--
Adam