Ruby-like Question: Make this function shorter (ActionScript 3)

前端 未结 9 1089
春和景丽
春和景丽 2021-01-14 01:38

I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 01:57

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

提交回复
热议问题