Ruby-like Question: Make this function shorter (Ac

2019-02-18 05:19发布

问题:

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

    public static function format(n:int, minimumLength:int):String {
        var retVal:String = n.toString();
        var stillNeed:int = minimumLength - retVal.length;
        for (var i:int = 0; i < stillNeed; i++) {
            retVal = "0" + retVal;
        }
        return retVal;
    }

Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.

If anybody wants to post some extremely short equivalent in some other language, that would be fun too.

回答1:

This wouldn't be the fastest implementation (it does some unnecessary copying and has a loop), but it is nice and readable:

public static function pad(num:int, minLength:uint):String {
    var str:String = num.toString();
    while (str.length < minLength) str = "0" + str;
    return str;
}


回答2:

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.



回答3:

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


回答4:

How about this:

public static function format(n:int, len:int):String {
  var v:String = n.toString();
  return (v.length >= len) ? v : String(Math.pow(10, len) + n).substr(1);
}

There is not built-in function to do this btw. If you need decent padding functions, take a look at the StringUtils in Apache Commons Lang.



回答5:

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


回答6:

"If anybody wants to post some extremely short equivalent in some other language, that would be fun too."

In javascript it is easy - paste this into your browser's address bar

javascript: function zit(n, w) {var z="000000000000000000"; return (z+n).substr(-w);} alert(zit(567, 9)); void(0);



回答7:

I've always done this by taking a string that is the maximum padded width of zeros containing all zeros, then appeneding the string to padded to the end of the zeros string and then using substring to get the right hand Length digits.

Something like:

function pad(num:int, length:unit):String{
    var big_padded:String "0000000000000000000000000000" + num.toString();
    return big_padded.substring(big_padded.length - length);
 }


回答8:

The as3corelib package put out by adobe has a nice little NumberFormatter class that uses a series of STATIC classes. In this case you could use the addLeadingZero function.

//The following method is from the NumberFormatter class of the as3corelib package by Adobe.
public static function addLeadingZero(n:Number):String
{
var out:String = String(n);

if(n < 10 && n > -1)
{
    out = "0" + out;
}

return out;
}

I included the function just to show it's simplicity, but I would use the package instead of yoinking the function because it provides many other useful features like StringUtils, encryption methods like MD5, blowfish, etc.

You can download the package here For newer users you must provide a classpath to where this package lives. It is also smart to import the classes instead of using their fully qualified class names.



回答9:

private function leadingZeros(value:int, numDigits:int):String
{
            return String(new Array(numDigits + 1).join("0") + String(value)).substr(-numDigits, numDigits);
}