This wasn't technically a 'Ask a Jedi' question but was posted to my forums. The question was - how can we convert numbers into smaller versions? The examples given by the user were:
123,000 to 123K
123,000,000 to 123M
123,000,000,000 to 123B
I checked CFlib of course, and the closest thing I found was ByteConvert. I played around a bit and came up with the following UDF:
<cfscript>
function formatKMB(x) {
if(x < 1000) return x;
if(x >= 1000 && x < 1000000) {
x = x/1000;
x = round(x);
return x & "K";
}
if(x >= 1000000 && x < 1000000000) {
x = x/1000000;
x = round(x);
return x & "M";
}
if(x >= 1000000000 && x < 1000000000000) {
x = x/1000000000;
x = round(x);
return x & "B";
}
return x;
}
</cfscript>
It's probably a bit more verbose then it needs to be but it handles numbers in the thousands (Ks), millions (Ms), and billions (Bs). I wrote up a quick test to see if it worked:
<cfset tests = "900,1002,1932,123000,432000,1000000,92000000,102000000000,2321903211">
<cfloop index="t" list="#tests#">
<cfoutput>
#t#=#formatKMB(t)#<br />
</cfoutput>
</cfloop>
I'll post this to CFLib a bit later. First I'm going to remove the CF8 stuff (<, >) so it will work CF5 and higher.