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';
}
}
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';
}
}