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

前端 未结 9 1172
春和景丽
春和景丽 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:46

    Props to dirkgently and all others who have responded here, but apparently people are voting up without actually trying the code.

    dirkgently's final function is mostly correct, but his '>' needs to be a '<'.

    This function performs as desired (tested fairly thoroughly):

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

提交回复
热议问题