2011-01-19 141 views
12

double类型的变量,我需要打印在高达的精度3位小数,但它不应该有任何尾随零...格式化浮点数

如。我需要

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

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

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

谢谢。 :)

回答

21

尝试模式"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)); 
     } 
    } 
} 

输出:

2.5 
2 
1.375 
2.12 
+0

@ st0le,欢呼! – 2011-01-19 08:35:56

4

使用NumberFormat类。

实施例:

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

输出将是2.5,而不是2.500。

6

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

因此,它应该是这样的:

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

这行不necesary(如decimalSeparatorAlwaysShownfalse默认):

myFormatter.setDecimalSeparatorAlwaysShown(false); 

下面是从的javadoc简短的摘要:

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

并链接到javadoc:DecimalFormat

+0

+1为额外的信息。 – st0le 2011-01-19 09:25:03