I've written code to compute Levenshtein distance between two strings and give output like in floating point format with numbers after the decimal point.
How can I format the output to display two digits after the decimal point? I don't know how to do this in Java, but I know in C I would use something like .%2.f.
Here is the code:
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");
}
}
edit, I mean the return of the method public double similarity
or the method printDistance
.
Its because, in another class when i create an object this class, I need the return with format 0.00