【问题标题】:Efficient way of adding zeros to a String number?将零添加到字符串数字的有效方法?
【发布时间】:2015-04-26 13:38:47
【问题描述】:

我想将所有值转换为以下数字格式,x.xxx。我通过使用 while 循环并将 0 连接到长度不正确的字符串值来做到这一点。但是,我想知道是否有更有效的方法来做到这一点。为了更清楚我想要做什么,这里有一些例子。

Ex1--将字符串值如2.5改为2.500 Ex2--将2.51等字符串值改为2.510。

这就是我目前的做法。

while (str.length() < 5) {
    str= str+ "0";
}

【问题讨论】:

    标签: java android string-concatenation


    【解决方案1】:

    您可以使用DecimalFormat

    DecimalFormat decimalFormat = new DecimalFormat("0.000"); 
    System.out.println(decimalFormat.format(2.5));
    

    【讨论】:

    • 是的,这样干净多了!谢谢!
    • 别忘了接受答案,你的问题就解决了。 @portfoliobuilder
    • 一旦系统允许我接受这个答案。谢谢你!
    【解决方案2】:

    哇,那是一个了不起的Reimeus!

    无论如何,这是怎么回事? :P

    int totalLenght = str.length();
    
            if(totalLenght>5){
                str = str.substring(0,5);
            }else{
                int remLength = 5 - totalLenght;
    
                for(int i=0;i<remLength;i++){
                    str = str +"0";
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      • 2019-08-17
      • 1970-01-01
      相关资源
      最近更新 更多