类似 Ruby 的问题:让这个函数更短(ActionScript 3)

发布于 2024-07-14 16:52:50 字数 493 浏览 7 评论 0原文

我刚刚编写了一段极其冗长的代码,将 2 这样的数字转换为 02。您能否缩短此函数(维护功能)?

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

请使用变量类型。 如果已经有我不知道的内置功能,则额外加分(良好氛围加分,而不是SO加分)。

如果有人想用其他语言发布一些极其简短的等效内容,那也会很有趣。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

笑忘罢 2024-07-21 16:52:50

这不是最快的实现(它进行了一些不必要的复制并有一个循环),但它很好并且可读:

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

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;
}
開玄 2024-07-21 16:52:50

我不认为有内置的方法,但这可能更干净(如果不一定性能更好):

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

“zeroes”var消除了循环的需要,只需从预构建的字符串中添加您需要的任意多个零即可。

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.

满天都是小星星 2024-07-21 16:52:50

Christophe Herreman 几乎是对的,但他的方法添加了更多的零,而不是差值。 我修复了一点:

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

我之前的尝试:

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

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);
 }
假面具 2024-07-21 16:52:50

怎么样:

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

顺便说一句,没有内置函数可以执行此操作。 如果您需要合适的填充功能,请查看 StringUtils

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.

醉生梦死 2024-07-21 16:52:50

支持 dirkgently 和所有其他在这里做出回应的人,但显然人们在没有实际尝试代码的情况下就投票了。

dirkgently 的最终函数大部分是正确的,但他的 '>' 需要是“<”。

该函数按预期执行(经过相当彻底的测试):

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

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);
}
不甘平庸 2024-07-21 16:52:50

“如果有人想发布一些
某些方面极其短等价
其他语言,那也会很有趣。”

在 javascript 中这很容易 - 将其粘贴到浏览器的地址栏

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

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

心的憧憬 2024-07-21 16:52:50

我总是通过获取一个包含所有零的零的最大填充宽度的字符串来完成此操作,然后将要填充的字符串附加到零字符串的末尾,然后使用子字符串来获取右侧的长度数字。

就像是:

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

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);
 }
水溶 2024-07-21 16:52:50

adobe 推出的 as3corelib 包有一个漂亮的小 NumberFormatter 类,它使用一系列 STATIC 类。 在这种情况下,您可以使用 addLeadingZero 函数。

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

我包含该函数只是为了显示它的简单性,但我会使用该包而不是使用该函数,因为它提供了许多其他有用的功能,如 StringUtils、加密方法(如 MD5、blowfish 等)。

您可以下载该包 此处
对于新用户,您必须提供该包所在位置的类路径。 导入类而不是使用它们的完全限定类名也是明智的做法。

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.

鹿童谣 2024-07-21 16:52:50
private function leadingZeros(value:int, numDigits:int):String
{
            return String(new Array(numDigits + 1).join("0") + String(value)).substr(-numDigits, numDigits);
}
private function leadingZeros(value:int, numDigits:int):String
{
            return String(new Array(numDigits + 1).join("0") + String(value)).substr(-numDigits, numDigits);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文