I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?
Christophe Herreman almost got it right, but his method adds more zeroes and not the differential amount. I fixed it a bit:
public static function format(n:int, minimumLength:int):String {
var v:String = n.toString();
var stillNeed:int = minimumLength - v.length;
return (stillNeed > 0) ? v : String(Math.pow(10, stillNeed) + v).substr(1);
}
My earlier try:
public static function format(n:int, minimumLength:int):String {
var stillNeed:int = minimumLength - n.toString().length;
return (n.split("").reverse().join("") as int) // 32 -> 23
*Math.pow(10, stillNeed > 0 ? stillNeed : 0).toString() // 23000
.split("").reverse().join(""); // 00032
}
public static function formatAny(n:Number, minimumLength:int):String {
return format((int)n) + n.toString().split('.')[ 1 ];
}
// use this if you want to handle -ve numbers as well
public static function formatAny(n:Number, minimumLength:int):String {
return (n < 0 ? '-' : '') + formatAny(n, minimumLength);
}