This function will add commas to a given number passed as a string, separating thousands, millions, etc. Rather than doing long division to figure out how many "digit groups" there are, it simply reverses the number string, adds the commas after every third digit (after the decimal place, if present), and then re-reverses the string for return.
Examples:
PRINT dbo.fn_AddCommasToNumberString('20123.12') -- 20,123.12 PRINT dbo.fn_AddCommasToNumberString('2012312') -- 2,012,312 PRINT dbo.fn_AddCommasToNumberString('23') -- 23
Written by Jesse McLain