【问题标题】:Number formatting with two digits after decimal point in Java [duplicate]Java中小数点后两位数字格式[重复]
【发布时间】:2014-08-18 19:44:44
【问题描述】:

我编写了代码来计算两个字符串之间的 Levenshtein 距离,并以浮点格式给出输出,小数点后有数字。

如何格式化输出以显示小数点后两位?我不知道如何在 Java 中做到这一点,但我知道在 C 中我会使用类似 .%2.f 的东西。

代码如下:

package algoritma.LevenshteinDistance;

public class LevenshteinDistance {

String hasilPersen;

public String getHasilPersen() {
    return hasilPersen;
}

public void setHasilPersen(String hasilPersen) {
    this.hasilPersen = hasilPersen;
}

public LevenshteinDistance() {

}

public double similarity(String s1, String s2) {
    if (s1.length() < s2.length()) { // s1 should always be bigger
        String swap = s1;
        s1 = s2;
        s2 = swap;
    }
    int bigLen = s1.length();
    if (bigLen == 0) {
        return 1.0; /* both strings are zero length */ }
    return (bigLen - computeEditDistance(s1, s2)) / (double) bigLen;
}

public  int computeEditDistance(String s1, String s2) {
    s1 = s1.toLowerCase();
    s2 = s2.toLowerCase();

    int[] costs = new int[s2.length() + 1];
    for (int i = 0; i <= s1.length(); i++) {
        int lastValue = i;
        for (int j = 0; j <= s2.length(); j++) {
            if (i == 0) {
                costs[j] = j;
            } else {
                if (j > 0) {
                    int newValue = costs[j - 1];
                    if (s1.charAt(i - 1) != s2.charAt(j - 1)) {
                        newValue = Math.min(Math.min(newValue, lastValue),
                                costs[j]) + 1;
                    }
                    costs[j - 1] = lastValue;
                    lastValue = newValue;
                }
            }
        }
        if (i > 0) {
            costs[s2.length()] = lastValue;
        }
    }
    return costs[s2.length()];
}

public String printDistance(String s1, String s2) {
    System.out.println("[Edit Distance]       " + s1 + " and " + s2  + " " +similarity(s1, s2) * 100 + "%");
    return  similarity(s1, s2) * 100 + " % ";
}

public static void main(String[] args) {


    LevenshteinDistance lv = new LevenshteinDistance();


  lv.printDistance("841644761164234287878797", "841644487611642341");

}

}

编辑,我的意思是返回方法 public double similarity 或方法 printDistance 。 这是因为,在另一个类中,当我创建这个类的对象时,我需要格式为 0.00 的返回

【问题讨论】:

  • Java 的 String.format 基本类似于 C 的 sprintf。
  • 如果您所关心的只是将浮点数格式化为字符串,您可以将代码示例缩减为仅此,这样我们就不必费力地处理额外和不相关的信息(但是你想出你需要格式化的数字是无关紧要的)。

标签: java decimal


【解决方案1】:

这里有几种方法:

    double number = 678.675379823;
    System.out.printf("%.2f", number);

如果您想将结果保存在字符串中

    String no = String.format("%.2f", number);
    System.out.println("Formatted no :"+no);

java.text.DecimalFormat 是一种简洁、干净和简单的方式,可以将数字格式化为 n 位小数。

    NumberFormat formatter = new DecimalFormat("##.00");
    System.out.println(formatter.format(number));

虽然java.text.DecimalFormat 是一个不错的实用程序类,并且允许您在 Java 中动态格式化数字,但它有一个问题是它不是线程安全的或同步的。所以在 multi-线程环境正确。

【讨论】:

    【解决方案2】:

    你可以使用这样的东西:

    public class DecimalPlaces {
    
        public static void main(String[] args) {
    
            double d = 1.234567;
            System.out.printf("%1$.2f", d);
        }
    
    }
    

    public void GetTwoDecimal(){
    
            double d = 2.34568;
            DecimalFormat f = new DecimalFormat("##.00");  // this will helps you to always keeps in two decimal places
            System.out.println(f.format(d)); 
    }
    

    【讨论】:

      【解决方案3】:

      使用:

       DecimalFormat df = new DecimalFormat("#.00");
       df.format(your_decimal_value)
      

      【讨论】:

        【解决方案4】:

        使用System.out.printf(String formatString, Object... args)

        System.out.printf("[Edit Distance]       %.2f and %.2f %.2f%%%n", s1, s1,
                 similarity(s1, s2) * 100);
        

        Here's the documentation on format strings

        一些相关的摘录(该文档很长而且有点混乱):

        • 通用、字符和数字类型的格式说明符具有以下语法:

          %[argument_index$][flags][width][.precision]conversion

          • 可选的argument_index 是一个十进制整数,表示参数在参数列表中的位置。第一个参数由“1$”引用,第二个由“2$”引用,依此类推。

          • 可选的标志是一组修改输出格式的字符。有效标志集取决于转换。

          • 可选的宽度是一个非负十进制整数,表示要写入输出的最小字符数。

          • 可选的precision是一个非负十进制整数,通常用于限制字符数。具体行为取决于转换。

          • 所需的conversion 是一个字符,指示应如何格式化参数。给定参数的有效转换集取决于参数的数据类型。

        【讨论】:

          【解决方案5】:

          可以使用DecimalFormat,我将相似度乘以100后使用。代码如下,希望对您有所帮助。

          import java.awt.Graphics;
          import java.text.DecimalFormat;
          
          import javax.swing.JFrame;
          
          public class LevenshteinDistance {
          
              String hasilPersen;
          
              public String getHasilPersen() {
                  return hasilPersen;
              }
          
              public void setHasilPersen(String hasilPersen) {
                  this.hasilPersen = hasilPersen;
              }
          
              public LevenshteinDistance() {
          
              }
          
              public double similarity(String s1, String s2) {
                  if (s1.length() < s2.length()) { // s1 should always be bigger
                      String swap = s1;
                      s1 = s2;
                      s2 = swap;
                  }
                  int bigLen = s1.length();
                  if (bigLen == 0) {
                      return 1.0; /* both strings are zero length */
                  }
          
                  return (bigLen - computeEditDistance(s1, s2))
                          / (double) bigLen;
              }
          
              public int computeEditDistance(String s1, String s2) {
                  s1 = s1.toLowerCase();
                  s2 = s2.toLowerCase();
          
                  int[] costs = new int[s2.length() + 1];
                  for (int i = 0; i <= s1.length(); i++) {
                      int lastValue = i;
                      for (int j = 0; j <= s2.length(); j++) {
                          if (i == 0) {
                              costs[j] = j;
                          } else {
                              if (j > 0) {
                                  int newValue = costs[j - 1];
                                  if (s1.charAt(i - 1) != s2.charAt(j - 1)) {
                                      newValue = Math.min(Math.min(newValue, lastValue),
                                              costs[j]) + 1;
                                  }
                                  costs[j - 1] = lastValue;
                                  lastValue = newValue;
                              }
                          }
                      }
                      if (i > 0) {
                          costs[s2.length()] = lastValue;
                      }
                  }
                  return costs[s2.length()];
              }
          
              public String printDistance(String s1, String s2) {
          
                  double result = similarity(s1, s2);
                  double times100 = result * 100;
                  DecimalFormat decimalFormat = new DecimalFormat("0.00");
                  Double formattedResult = Double.parseDouble(decimalFormat.format(times100));
          
                  System.out.println("[Edit Distance]       " + s1 + " and " + s2 + " "
                          + formattedResult + "%");
                  return formattedResult + " % ";
              }
          
              public static void main(String[] args) {
          
                  LevenshteinDistance lv = new LevenshteinDistance();
          
                  lv.printDistance("841644761164234287878797", "841644487611642341");
          
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2011-03-22
            • 1970-01-01
            • 1970-01-01
            • 2011-05-23
            • 2016-10-04
            • 1970-01-01
            • 1970-01-01
            • 2021-07-25
            相关资源
            最近更新 更多