PDA

Volledige versie bekijken : open source initiatief Flashfocus!


De Kale
%Europe/Berlin %488 %2005, 12:42
Hi All,

ik moest gisteren met spoed een nummer formatteer functie bouwen en heb dit vanochtend nog een beetje uitgewerkt.
Ik heb het helemaal gebaseerd op de php's number_format functie en wilde het even delen met jullie.
EN.... ik wilde ook voorstellen dat mensen hier iets aan toevoegen :P
Dat hoeft niet zozeer de format() methode te zijn, maar kunnen ook andere handige methods zijn die te maken hebben met Number Formatting (zie ook de class naam!)

Verbeteringen zijn welkom, ik zal ongetwijfeld nog wat dingen vergeten zijn of er zullen wat bugs inzitten of optimalisatie slagen te doen zijn, maar ik wilde hier enkel de basis neerzetten ;)

Bekijk voordat je iets verandert of iemand anders niet toevallig net iets toegevoegd heeft aan de class, en TEST vantevoren uitgebreid je methods!

Veel plezier

In Flash:

var n = '000.603';
var n = '-000.603';
var n = 1234.603;
var n = -123456789.123456789;



trace('input: '+n+' output: '+classes.NumberFormat.format(n, 5, ',','.'));
trace('--------------');
trace('input: '+n+' output: '+classes.NumberFormat.format(n, -1, ',','.'));
trace('--------------');
trace('input: '+n+' output: '+classes.NumberFormat.format(n, -5, ','));


en de class hier (let op: hij staat in de directory classes tov van de flash file!!!! :) ):

/**
* The NumberFormat class is a class written to use as a tool for number formatting
* Project initiated by Rolf Vreijdenberger (www.depannekoekendekale.nl) to mimic PHP's number_format method
* @author Rolf Vreijdenberger
* @version 1.0
*
*
*
*/

class classes.NumberFormat{



/**
* ! This method is an exact copy of the working of PHP's number_format() function !
* From the PHP Manual:
* -----
* Format a number with grouped thousands
* string format ( float inputNumber [, int numberDecimals] )
* string format ( float inputNumber, int numberDecimals, string decimalString, string thousandsSeparator )
* format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):
* If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.
* If two parameters are given, number will be formatted with numberDecimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.
* If all four parameters are given, number will be formatted with numberDecimals decimals, decimalString instead of a dot (".") before the decimals and thousandsSeparator instead of a comma (",") between every group of thousands.
* Only the first character of thousandsSeparator is used. For example, if you use foo as thousandsSeparator on the number 1000, format() will return 1f000.
* -----
*
* @author Rolf Vreijdenberger
* @version 1.0
* @param inputNumber a Number that needs to be formatted
* @param numberDecimals the number of decimals in the formatting
* @param decimalString the string with the decimal separator (if more than one character, only the first character is used)
* @param thousandsSeparator the string with the seperator for the parts that are a power of 1000 (if more than one character, only the first character is used)
* @return the string representation of the original inputNumber with the formatting applied
*/
static function format(inputNumber: Number, numberDecimals: Number, decimalString: String, thousandsSeparator: String){
//TODO: optimize, use less variables, better variable names and cleaner algorithm


//declaration and initialization of temporary variables
var output: String = '';
var sign: String;
var tmpInt: Number;
var tmpIntString: String;
var tmpThousands: Number;
var tmpPreThousands: Number;
var tmpFloatString: String;
var hasDecimals: Number;
var tmpDecimalsString: String = '';
var tmpDecimalsNumber: Number;
var pad: String = '0';
var padHowMany: Number;



//sanity checks, to conform to php's number_format signature

//get the sign, positive or negative, to append to the output string
sign = inputNumber < 0 ? '-' : '';

//get positive inputNumber
inputNumber = Math.abs(inputNumber);

//check if we have the second parameter defined
if(numberDecimals == undefined ){
numberDecimals = 0;
thousandsSeparator = ',';
}

//sanitize, no negative numbers for decimal places
if(numberDecimals < 0 ){
numberDecimals = 0;
}


if(decimalString == undefined){//default for the decimalString
decimalString = '.';
thousandsSeparator = ',';
}else{//decimalString (third parameter) is given, now check if we have four parameters!
if(thousandsSeparator == undefined){//no, so we quit with some warnings and return the original input
trace(toString() +': Wrong parameter count for format()');
trace(toString() + '.format() requires 1, 2 or 4 parameters');
output = sign + inputNumber;
return output;
}
}

//only use the first character
if(decimalString.length > 1){
decimalString = decimalString.substr(0,1);
}

//default value
if(thousandsSeparator == undefined){
thousandsSeparator = '';
}

//only use the first character
if(thousandsSeparator.length > 1){
thousandsSeparator = thousandsSeparator.substr(0,1);
}

//according to the number of decimals, either get the rounded integer part, or the integer part of the original input
tmpInt = numberDecimals == 0 ? Math.round(inputNumber) : Math.floor(inputNumber) ;
//trace('tmpInt: '+tmpInt);

//get the string version of the input number (Integer), by casting it to String
tmpIntString = String(tmpInt);
//trace('tmpIntString: '+tmpIntString);

//get the number of powers of 1000, so we know how many separators we should use (eg.: '1000' has a string length of 4, so divide this by 3 and take the Math.floor() version of this, and we know we have '1' as the outcome, which means we have to implement 1 separator
tmpThousands = Math.floor(tmpIntString.length / 3);
//trace('tmpThousands: '+tmpThousands);

//get the part that comes before a thousand separator, by using modulo (eg.: '8234' has a string length of 4, so the modulo gives us '1'. we can use this to get the number before the first thousand separator
tmpPreThousands = tmpIntString.length % 3;
//trace('tmpPreThousands: '+tmpPreThousands);


//now start building the output string, first we get the part that comes before any thousands separator (if any)
output += tmpIntString.substr(0,tmpPreThousands);


//for all the thousands we need to separate, loop!
for(var i=0; i<tmpThousands; ++i){
//trace('looping: '+tmpIntString.substr(1 + (i*3),3))

//if we have a number before the separator, append the separator (else we have a number like '999', which wouldn't need a separator)
if(output != ''){
output += thousandsSeparator;
}

//add the part we need to the output
output += tmpIntString.substr(tmpPreThousands + (i*3),3)
}
//trace('output after thousandsSeparator: ' + output);

//if we need to display decimals, add the decimal string
if(numberDecimals > 0){
output += decimalString;
}

//get the whole input number(float) and convert it to a string
tmpFloatString = String(inputNumber);
//trace('tmpFloatString: '+tmpFloatString);

//check if there already are decimals present
//returns the place in the string where the '.' is, else -1
hasDecimals = tmpFloatString.indexOf('.');
//trace('hasDecimals: '+ hasDecimals);

//if we need to append the decimal fraction, enter this condition
if(hasDecimals != -1 && numberDecimals > 0){

//get the decimal fraction, by going from the position of the decimal point (+1) to the end of the string
tmpDecimalsString = tmpFloatString.substr(hasDecimals + 1);//, tmpFloatString.length - hasDecimals
//trace('tmpDecimalsString: '+tmpDecimalsString);

//now check the number of decimals we need to display
//if the decimal fraction consists of more numbers than we want to display, enter the next condition
if(tmpDecimalsString.length > numberDecimals){

//convert back to decimals (number, float)
tmpDecimalsNumber = parseFloat('.'+tmpDecimalsString);
//trace('tmpDecimalsNumber: '+tmpDecimalsNumber);

//overwrite the string, with the new value (rounded to the right number of decimals)
tmpDecimalsString = String( Math.round(tmpDecimalsNumber * Math.pow(10, numberDecimals) ) / Math.pow(10,numberDecimals));
//trace('tmpDecimalsString (after rounding to new value): '+tmpDecimalsString);

//overwrite with new value, where we take off the normal decimal point from the input number (float)
tmpDecimalsString = tmpDecimalsString.substr(tmpDecimalsString.indexOf ('.') +1);//,tmpDecimalsString.length
//trace('tmpDecimalsString (after substring extraction without decimal point): '+tmpDecimalsString);
}



}

//right pad, if necessary
//check how many pads we need
padHowMany = Math.abs(numberDecimals - tmpDecimalsString.length);

//the padding loop
for(var i=0; i<padHowMany; ++i){
tmpDecimalsString = tmpDecimalsString + pad;
}
//trace('tmpDecimalsString (after padding (' + padHowMany + ')): '+tmpDecimalsString);

//append the decimals to the output string
output += tmpDecimalsString;

//prefix the output string with the sign of the input number
output = sign + output;

//and return the result of our hard work ;)
return output;


}

/**
* method that returns the className, used to generate trace's from inside the classes method's
*
* @author Rolf Vreijdenberger
* @version 1.0
* @return the string representation of the className
* @see #format()
*/
static public function toString(): String{
return 'NumberFormat';
}

}

Tha Narie
%Europe/Berlin %515 %2005, 13:22
Ik zie een import nl.flashfocus.* package aankomen :P

Dauntless
%Europe/Berlin %547 %2005, 14:08
Ik zie een import nl.flashfocus.* package aankomen :P
Hé, ja! Maken we die niet? :D

Iasonic
%Europe/Berlin %025 %2005, 01:36
Hmm je zij dat je het gebaseerd hebt op php, maar volgens mij bedoel je javascript.
Het is ook niet echt duidelijk wat dit script zou moeten doen behalve getallen omzetten.
Ik zou niet weten wat er verder nog meer bij zou moeten zitten. Als je misschien wat duidelijker bent!

Jah of ik snap er gewoon geen **** van?
Laat ik het zo zeggen wat wil je er nog bij?

De Kale
%Europe/Berlin %347 %2005, 09:20
actionscript en javascript zijn beide gebaseerd op dezelfde standaard, deze class heeft als bedoeling om de php functie www.php.net/number_format helemaal qua functionaliteit na te bootsen...

en verder: laat je fantasie eens gaan, je doet vast wel eens wat aan nummer manipulatie ;)

Iasonic
%Europe/Berlin %453 %2005, 11:53
Ok nu is het wel duidelijk, ik zat dus de verkeerde kant uit te denken :)

Mediamonkey
%Europe/Berlin %629 %2005, 16:06
Het lijkt me inderdaad helemaal niet gek om een nl.flashfocus package op te zetten! Maar hoe dit te doen? Subforum? Sticky? Het moet wel duidelijk blijven.. Ik zou zeggen, maak een subforum aan binnen ASSC en maak een post per class waarin je een code voorstelt, in de groep gooit, waarop kan worden gereageerd en uiteindelijk aan de package kan worden toegevoegd.

De Kale
%Europe/Berlin %844 %2005, 21:16
goed, ik wil het hier weer wat leven inblazen, ook naar aanleiding van de nl.flashfocus package

hier is de uitdaging:

wie kan de sprintf() functie van PHP nabouwen in flash!!!
eeuwige roem kan je deel zijn ;)

Let op, deze is wel wat moelijker dan number_format....

een beginnetje is ook cool natuurlijk...

www.php.net/sprintf

Roenes
%Europe/Berlin %903 %2005, 22:40
Alsk van het weekend wat tijd heb zal ik eens kijken wat ik kan doen ;)

oh,when?
%Europe/Berlin %095 %2005, 03:16
goed, ik wil het hier weer wat leven inblazen, ook naar aanleiding van de nl.flashfocus package

hier is de uitdaging:

wie kan de sprintf() functie van PHP nabouwen in flash!!!

[...]
www.php.net/sprintf

*kuch* (http://natecook.com/downloads/sprintf.html) ;)

Folkert
%Europe/Berlin %885 %2005, 21:14
Het lijkt me inderdaad helemaal niet gek om een nl.flashfocus package op te zetten! Maar hoe dit te doen? Subforum? Sticky? Het moet wel duidelijk blijven.. Ik zou zeggen, maak een subforum aan binnen ASSC en maak een post per class waarin je een code voorstelt, in de groep gooit, waarop kan worden gereageerd en uiteindelijk aan de package kan worden toegevoegd.

dat klinkt goed, is dit realiseerbaar of moeten er andere oplossingen bedacht om deze trein op gang te brengen ?

Dauntless
%Europe/Berlin %888 %2005, 21:19
Kijk hier (http://flashfocus.nl/forum/showthread.php?t=5397) eens folkert :)

TheZwier
%Europe/Berlin %903 %2005, 21:40
dat klinkt goed, is dit realiseerbaar of moeten er andere oplossingen bedacht om deze trein op gang te brengen ?

Het idee zelf lijkt me redelijk realiseerbaar (geen nieuwe dingen toch?)
Ik zal af en toe kijken of ik ook een bruikbaar regeltje eruit kan persen, al is het maar sarcastisch commentaar :D


btw, folkert hoe heette je op het oude forum? Ik meen telkens maar iemand te hebben gekend (op het oude forum) die ook folkert ofzo heette...

De Kale
%Europe/Berlin %444 %2005, 10:39
*kuch* (http://natecook.com/downloads/sprintf.html) ;)

oke, dat heb je snel gedaan :-)
hehe, nou jah, er zijn genoeg andere speeltjes te bouwen!

Folkert
%Europe/Berlin %991 %2005, 23:47
btw, folkert hoe heette je op het oude forum? Ik meen telkens maar iemand te hebben gekend (op het oude forum) die ook folkert ofzo heette...
sja ook folkert denk ik of vroegah misschien nederflash nog ;) maar meen toch al lange tijd gewoon folkert