2017-10-12 54 views
0

如何格式化小數?格式化字符串0.2到2000

0.2顯示爲2000

我也想,即使是0值將顯示爲0000

+2

'* 10000'和'String.format' – 2017-10-12 10:46:26

+0

只是爲了我的理解:你想要打印0.2000? –

回答

0

你的問題不是真的完整,如果你想顯示十進制數的整數值(向上/向下取整),那麼你只需要* 10000然後將它舍入,然後格式化爲RC回答。

public static void main(String[] args) { 

    float original = 0.2f; 
    float multiplied = original *10000; 
    int intvalue = (int)multiplied; // you can change to round up/down 

    String d = String.format("%04d", intvalue); 
    System.out.println("Value d : "+d); 

} 

檢查這裏的格式https://dzone.com/articles/java-string-format-examples

0

這是假設所需的輸出是2000的解決方案:

System.out.println(String.format("%.4f", 0.2).replaceFirst("^0\\.", "")); 

同爲0000:

System.out.println(String.format("%.4f", 0.0).replaceFirst("^0\\.", "")); 

您可以使用以下方法:

private static String convert(double v) { 
    return String.format("%.4f", v).replaceFirst("^0\\.", ""); 
} 
+0

我需要從0.2和0000輸出2000以從0輸出 –

0

我錯在先。這裏是使用DecimalFormatter的正確答案,它適合你的情況。假設您已經定義double d;

DecimalFormat formatter = new DecimalFormat("#0000"); 
System.out.println(formatter.format(d * 10000)); 

輸出將被格式化爲使用#0000 4位。

0 -> 0000 
0.2 -> 2000 
0.8 -> 8000