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

前端 未结 9 1165
春和景丽
春和景丽 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 02:10

    I don't think there is a built-in way, but this might be cleaner (if not necessarily better performing):

    //20 zeroes, could be more if needed
    public static var Zeroes:String = "00000000000000000000"   
    
    public static function format(n:Number, minimumLength:int):String {
    var retVal:String = (n.toFixed(0)); // cut off the decimals
    var stillNeed:int = minimumLength - retVal.length;
    retVal = Zeroes.substring(0, stillNeed) + retVal; 
    return retVal;
    }
    

    The "zeroes" var eliminates the need for looping, just prepend however many zeroes you need from a prebuilt string.

提交回复
热议问题