Que voulez-vous utiliser à zéro pad un numéro dans Flex / AS3?
-
21-08-2019 - |
Question
Que voulez-vous utiliser pour pad à zéros à gauche d'un numéro dans Flex / AS3?
Y at-il un équivalent à ou printf
qui fait cela NumberFormat
?
Je cherche la plus belle mise en œuvre de ce ou quelque chose de similaire:
public function zeroPad(number:int, width:int):String {
// number = 46, width = 4 would return "0046"
}
La solution
public function zeroPad(number:int, width:int):String {
var ret:String = ""+number;
while( ret.length < width )
ret="0" + ret;
return ret;
}
Autres conseils
Côté performance, je préfère utiliser une chaîne constante et substr, comme ceci:
package {
public class Helper {
private static const _ZEROS:String = "0000000000000000000000000000000000000000"; // 40 zeros, shorten/expand as you wish
/*
* f: positive integer value
* z: maximum number of leading zeros of the numeric part (sign takes one extra digit)
*/
public static function uint_Zeropadded(f:uint, z:int = 0):String {
var result:String = f.toString();
while (result.length < z)
result = _ZEROS.substr(0, z - result.length) + result;
return result;
}
}
}
La chaîne a très peu footstamp constante par rapport aux performances draw-backs de l'extension de la chaîne, un par un chiffre plusieurs fois. Dans la plupart des cas (jusqu'à 40 zéros dans cet exemple) nombre d'instructions est le même pour tous les appels.
Phil variante comme un élégant récursion :
public function zeroPad (number:String, width:int):String {
if (number.length < width)
return "0" + zeroPad(number, width-1);
return number;
}
Je ne sais pas de ses performances sur AS3, mais il semble que plus frais! : -)
public static function getFormatedValue(num:Number, roundDecimalPlace:Number=2, showLastZerosInDecimalPlaces:Boolean = false, decimalSeparator:String=".", thousandsSeparator:String=",", currency:String="$"):String
{
//assigns true boolean value to neg in number less than 0
var neg:Boolean = (num < 0);
//make the number positive for easy conversion
num = Math.abs(num)
var roundedAmount:String = String(num.toFixed(roundDecimalPlace));
//split string into array for dollars and cents
var amountArray:Array = roundedAmount.split(".");
var dollars:String = amountArray[0]
var cents:String = amountArray[1]
//create dollar amount
var dollarFinal:String = ""
var i:int = 0
for (i; i < dollars.length; i++)
{
if (i > 0 && (i % 3 == 0 ))
{
dollarFinal = thousandsSeparator + dollarFinal;
}
dollarFinal = dollars.substr( -i -1, 1) + dollarFinal;
}
//create Cents amount and zeros if necessary
var centsFinal:String;
if(showLastZerosInDecimalPlaces)
{
centsFinal = String(cents);
var missingZeros:int = roundDecimalPlace - centsFinal.length;
if (centsFinal.length < roundDecimalPlace)
{
for (var j:int = 0; j < missingZeros; j++)
{
centsFinal += "0";
}
}
}
else
{
if(Number(cents) != 0)
{
centsFinal = String(String(Number("0."+cents)).split(".")[1]);
}
else
{
roundDecimalPlace = 0;
}
}
var finalString:String = ""
if (neg)
{
finalString = "-"+currency + dollarFinal
} else
{
finalString = currency + dollarFinal
}
if(roundDecimalPlace > 0)
{
finalString += decimalSeparator + centsFinal;
}
return finalString;
}
Exemple très court du zéro de remplissage (AS2) ...
Convert = function(Minutes) {
return ('00'+String(int(Minutes/60)%24)).substr(-2,2);
}
/**
* originally by Chris Agiasotis @ http://agitatedobserver.com/as3-currency-formatter/
* improved by Joseph Balderson @ http://www.joeflash.ca
*/
package
{
public class CurrencyFormat
{
public function CurrencyFormat(){ }
public function getCurrency(num:Number,
decimalSeparator:String=".",
decimalPlace:Number=2,
currency:String="$",
thousandsSeparator:String=","
):String
{
//assigns true boolean value to neg in number less than 0
var neg:Boolean = (num < 0);
//make the number positive for easy conversion
num = Math.abs(num)
var roundedAmount:String = String(num.toFixed(decimalPlace));
//split string into array for dollars and cents
var amountArray:Array = roundedAmount.split(".");
var dollars:String = amountArray[0]
var cents:String = amountArray[1]
//create dollar amount
var dollarFinal:String = ""
var i:int = 0
for (i; i < dollars.length; i++)
{
if (i > 0 && (i % 3 == 0 ))
{
dollarFinal = thousandsSeparator + dollarFinal;
}
dollarFinal = dollars.substr( -i -1, 1) + dollarFinal;
}
//create Cents amount and zeros if necessary
var centsFinal:String = String(cents);
var missingZeros:int = decimalPlace - centsFinal.length;
if (centsFinal.length < decimalPlace)
{
for (var j:int = 0; j < missingZeros; j++)
{
centsFinal += "0";
}
}
var finalString:String = ""
if (neg)
{
finalString = "-"+currency + dollarFinal
} else
{
finalString = currency + dollarFinal
}
if(decimalPlace > 0)
{
finalString += decimalSeparator + centsFinal;
}
return finalString;
}
}
}
Je maintiens un printf en AS3: Malheureusement, un débordement de pile ne me laisse pas poster des liens, mais si le nom du projet de code Google est printf-AS3
Vos commentaires sont toujours les bienvenus.
-
Une solution très compacte:
public function zeroPad(s:String,pad:int):String {
for(;s.length<pad;s='0'+s);
return s;
}