java 格式化浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4733089/
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-10-30 07:46:31  来源:igfitidea点击:

Formatting Floating Point Numbers

javastringfloating-pointdoublestring-formatting

提问by st0le

I have a variable of type double, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...

我有一个 type 变量double,我需要以最多 3 位小数的精度打印它,但它不应该有任何尾随零...

eg. I need

例如。我需要

2.5 // not 2.500
2   // not 2.000
1.375 // exactly till 3 decimals
2.12  // not 2.120

I tried using DecimalFormatter, Am i doing it wrong?

我尝试使用DecimalFormatter,我做错了吗?

DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);

Thanks. :)

谢谢。:)

回答by Bart Kiers

Try the pattern "0.###"instead of "0.000":

尝试模式"0.###"而不是"0.000"

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
        for(double d : tests) {
            System.out.println(df.format(d));
        }
    }
}

output:

输出:

2.5
2
1.375
2.12

回答by Marcin Pieciukiewicz

Your solution is almost correct, but you should replace zeros '0' in decimal format pattern by hashes "#".

您的解决方案几乎是正确的,但您应该用散列“#”替换十进制格式模式中的零“0”。

So it should look like this:

所以它应该是这样的:

DecimalFormat myFormatter = new DecimalFormat("#.###");

And that line is not necesary (as decimalSeparatorAlwaysShownis falseby default):

而该行不necesary(如decimalSeparatorAlwaysShownfalse默认):

myFormatter.setDecimalSeparatorAlwaysShown(false);

Here is short summary from javadocs:

以下是来自 javadocs 的简短摘要:

Symbol  Location    Localized?  Meaning
0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent

And the link to javadoc: DecimalFormat

以及指向 javadoc 的链接:DecimalFormat

回答by Rogach

Use NumberFormat class.

使用 NumberFormat 类。

Example:

例子:

    double d = 2.5;
    NumberFormat n = NumberFormat.getInstance();
    n.setMaximumFractionDigits(3);
    System.out.println(n.format(d));
    double d = 2.5;
    NumberFormat n = NumberFormat.getInstance();
    n.setMaximumFractionDigits(3);
    System.out.println(n.format(d));

Output will be 2.5, not 2.500.

输出将是 2.5,而不是 2.500。