我编写了代码来计算两个字符串之间的编辑距离,并以浮点格式给出小数点后数字的输出。
如何格式化输出以显示小数点后两位数字?我不知道如何在 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 的返回
最佳答案
这里有几种方法:
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中动态格式化数字,但它有一个问题,即它不是线程安全的或同步的。所以在多线程环境中要小心。
关于java - Java中小数点后两位数字的数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24456211/