Author Topic: Teying to emulate PHP number_format  (Read 492 times)

Code: [Select]
function formatNumber(%num)
{
%len = strLen(%num);
if(%len < 4)
return %num;

while(%len > 3)
{
%formatted = %formatted @ "," @ getSubStr(%num,%len-3,%len);
%len -= 3;
}
return getSubStr(%num,0,%len) @ %formatted;
}
This works up until you get to a 7-digit number. strLen seems to work until a 10-digit number is reached. Am i missing something here?

What happens with a 7 digit number?

echo(formatNumber(1234567));
1,567,2345

add %num = getSubStr(%num, 0, %len - 4); as the second line in your loop?

That pointed me in the right direction, thanks.
Code: [Select]
function formatNumber(%num)
{
%len = strLen(%num);
if(%len < 4)
return %num;
if(striPos(%num,"-") == 0)
{
%negative = "-";
%num = getSubStr(%num,1,%len);
%len--;
}
while(%len > 3)
{
%formatted = "," @ getSubStr(%num,%len-3,%len) @ %formatted;
%num = getSubStr(%num, 0, %len - 3);
%len -= 3;
}
return %negative @ %num @ %formatted;
}
Works with up to 6-digit negatives down to -999,999 and numbers up to 2,147,483,647, which is until Torque appears to mess it up.