0

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

user2971238
  • 75
  • 1
  • 2
  • 9
  • 2
    `String.format`? http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java?rq=1 – doctorlove Jun 27 '14 at 16:07
  • Java's String.format is basically like C's sprintf. – David Ehrmann Jun 27 '14 at 16:07
  • 1
    If all you're concerned about is just regarding formatting a float number as a string, you can pare down your code sample to just that, so we don't have to wade through extra and irrelevant information (however you come up with the number you need to format is irrelevant). – Santa Jun 27 '14 at 16:07

5 Answers5

4

Here are couple of ways :

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

If your want to hold the result in a String

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

java.text.DecimalFormat is neat, clean and simple way of formatting numbers upto n number of decimal places.

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

Though java.text.DecimalFormat is a nice utility class and allow you to dynamically format numbers in Java it has one problem that its not thread-safe or synchronized.So be careful in multi-threaded environment properly.

SparkOn
  • 8,193
  • 3
  • 23
  • 28
0

Use 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

Some relevant excerpts (that documentation is long and a bit confusing):

  • The format specifiers for general, character, and numeric types have the following syntax:

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

    • The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

    • The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.

    • The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.

    • The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.

    • The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

durron597
  • 30,764
  • 16
  • 92
  • 150
0

You can use something like this :

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");  // this will helps you to always keeps in two decimal places
        System.out.println(f.format(d)); 
}
Bla...
  • 6,972
  • 6
  • 25
  • 43
0

use:

 DecimalFormat df = new DecimalFormat("#.00");
 df.format(your_decimal_value)
Jens
  • 60,806
  • 15
  • 81
  • 95
0

DecimalFormat can be used and I use it after I have multiplied the similarity by 100.The code is below and hope it will help you.

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");

    }
}
Eugene
  • 8,507
  • 3
  • 35
  • 55