简体   繁体   English

格式化浮点数

[英]Formatting Floating Point Numbers

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... 我有一个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. 谢谢。 :) :)

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

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 decimalSeparatorAlwaysShown is false by default): 并且该行不是decimalSeparatorAlwaysShown的(默认情况下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的链接

Use NumberFormat class. 使用NumberFormat类。

Example: 例:

  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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM