View Single Post
  #1  
Old 04-16-2011, 02:23 AM
fowlplay4 fowlplay4 is offline
team canada
fowlplay4's Avatar
Join Date: Jul 2004
Location: Canada
Posts: 5,200
fowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond reputefowlplay4 has a reputation beyond repute
Number Separator / Formatter

It's a lot easier to make out a million when it's written as 1,000,000 instead of 1000000.

Function:

separate(value, [separator]);

If separator isn't passed it uses a comma.

PHP Code:
function separate(valsep) {
  
// Set chars to separate numbers by
  
temp.chars 3;
  
// Negative Number Support
  
if (val 0) {
    
val *= -1;
    
temp.negative true;
  } else {
    
temp.negative false;
  }
  
// Check if requires separation
  
if (val >= (10 temp.chars)) {
    
// Decimal Support
    
temp.dpos val.pos(".");
    if (
temp.dpos >= 0) {
      
temp.newval val.substring(temp.dpos);
    } else {
      
temp.dpos val.length();
    }
    
// Begin Separating Numbers
    
for (temp.temp.dpos temp.charstemp.0temp.-= temp.chars) {
      
temp.newval = (sep sep ",") @ val.substring(temp.itemp.chars) @ temp.newval
    }
    
// Append Final Section of Number
    
temp.newval val.substring(0temp.chars abs(temp.i)) @ temp.newval;
    
// Make negative if neccesary
    
if (temp.negativetemp.newval "-" temp.newval;
    
// Return Separated Value
    
return temp.newval;
  } else {
    
// Make negative if neccesary and return value
    
return val * (temp.negative ? -1);
  }

Usage:

PHP Code:
function onCreated() {
  for (
temp.0temp.10temp.i++) {
    echo(
separate(10 temp.i));
  }
  for (
temp.0temp.6temp.i++) {
    echo(
separate(-(10 temp.i) + 0.15));
  }

Output:

PHP Code:
1
10
100
1
,000
10
,000
100
,000
1
,000,000
10
,000,000
100
,000,000
1
,000,000,000

-0.85
-9.85
-99.85
-999.85
-9,999.85
-99,999.85 
__________________
Quote:

Last edited by fowlplay4; 04-16-2011 at 06:32 AM.. Reason: Decimal, Negative Value Support + Updated Usage and Output
Reply With Quote