【发布时间】: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 的返回
【问题讨论】:
-
String.format? stackoverflow.com/questions/153724/… -
Java 的 String.format 基本类似于 C 的 sprintf。
-
如果您所关心的只是将浮点数格式化为字符串,您可以将代码示例缩减为仅此,这样我们就不必费力地处理额外和不相关的信息(但是你想出你需要格式化的数字是无关紧要的)。