Graal Forums

Graal Forums (https://forums.graalonline.com/forums/index.php)
-   Code Gallery (https://forums.graalonline.com/forums/forumdisplay.php?f=179)
-   -   Number Seperator Formatter (https://forums.graalonline.com/forums/showthread.php?t=134262839)

fowlplay4 04-16-2011 02:23 AM

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 


cbk1994 04-16-2011 02:28 AM

A lot nicer than the one I wrote, thanks for sharing.

Tigairius 04-16-2011 06:04 AM

Doesn't work for negatives or numbers containing a decimal.

fowlplay4 04-16-2011 06:23 AM

Quote:

Originally Posted by Tigairius (Post 1643640)
Doesn't work for negatives or numbers containing a decimal.

Right, added it in.


All times are GMT +2. The time now is 05:39 PM.

Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2026, vBulletin Solutions Inc.
Copyright (C) 1998-2019 Toonslab All Rights Reserved.