Number formatting with two digits after decimal point in Java -
i've written code compute levenshtein distance between 2 strings , give output in floating point format numbers after decimal point.
how can format output display 2 digits after decimal point? don't know how in java, know in c use .%2.f.
here 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 bigger string swap = s1; s1 = s2; s2 = swap; } int biglen = s1.length(); if (biglen == 0) { return 1.0; /* both strings 0 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]; (int = 0; <= s1.length(); i++) { int lastvalue = i; (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 + " , " + 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, mean return of method public double similarity
or method printdistance
. because, in class when create object class, need return format 0.00
you can use :
public class decimalplaces { public static void main(string[] args) { double d = 1.234567; system.out.printf("%1$.2f", d); } }
or
public void gettwodecimal(){ double d = 2.34568; decimalformat f = new decimalformat("##.00"); // helps keeps in 2 decimal places system.out.println(f.format(d)); }
Comments
Post a Comment