Java中小数点后两位数的数字格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24456211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:18:57  来源:igfitidea点击:

Number formatting with two digits after decimal point in Java

javadecimal

提问by user2971238

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.

我已经编写了代码来计算两个字符串之间的 Levenshtein 距离,并以浮点格式输出小数点后的数字。

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.

如何格式化输出以在小数点后显示两位数?我不知道如何在 Java 中执行此操作,但我知道在 CI 中会使用类似 .%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 similarityor the method printDistance. Its because, in another class when i create an object this class, I need the return with format 0.00

编辑,我的意思是方法public double similarity或方法的返回printDistance。这是因为,在另一个类中,当我创建这个类的对象时,我需要返回格式为 0.00

回答by durron597

Use System.out.printf(String formatString, Object... args).

使用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_indexis 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 flagsis a set of characters that modify the output format. The set of valid flags depends on the conversion.

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

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

    • The required conversionis 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.

  • 常规、字符和数字类型的格式说明符具有以下语法:

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

    • 可选的argument_index是一个十进制整数,表示参数在参数列表中的位置。第一个参数由“1$”引用,第二个参数由“2$”引用,依此类推。

    • 可选标志是一组修改输出格式的字符。有效标志集取决于转换。

    • 可选宽度是一个非负十进制整数,表示要写入输出的最小字符数。

    • 可选精度是一个非负十进制整数,通常用于限制字符数。具体行为取决于转换。

    • 所需的转换是一个字符,指示应如何格式化参数。给定参数的有效转换集取决于参数的数据类型。

回答by Bla...

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

回答by Jens

use:

用:

 DecimalFormat df = new DecimalFormat("#.00");
 df.format(your_decimal_value)

回答by Eugene

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.

可以使用DecimalFormat,我将相似度乘以100后使用它。代码如下,希望对您有所帮助。

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

    }
}

回答by SparkOn

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.DecimalFormatis neat, clean and simple way of formatting numbers upto n number of decimal places.

java.text.DecimalFormat是将数字格式化为 n 位小数的整洁、干净和简单的方法。

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

Though java.text.DecimalFormatis 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 environmentproperly.

虽然java.text.DecimalFormat是一个不错的实用程序类,并允许您在 Java 中动态格式化数字,但它有一个问题,即它不是线程安全的或同步的。所以在多线程环境中要小心。