簡體   English   中英

如何使用字符串生成器在java中打印最多兩個小數位?

[英]How to print upto two decimal places in java using string builder?

嗨我在分割字符串構建器和打印后嘗試打印字符串構建器讓我看看我的代碼,

string.append("Memomry usage:total:"+totalMemory/1024/1024+
"Mb-used:"+usageMemory/1024/1024+
" Mb("+Percentage+"%)-free:"+freeMemory/1024/1024+
" Mb("+Percentagefree+"%)");

在上面的代碼“totalmemory”和“freememory”是雙重類型,其中字節值不為空,所以我將它除以“1024”兩次得到它在“Mb”中,“string”是字符串生成器的變量后使用它代碼我只是打印它得到的結果,如下所示,

Used Memory:Memomry usage: 
total:13.3125Mb-used:0.22920989990234375Mb (0.017217645063086855%)
-free:13.083290100097656Mb (0.9827823549369131%)

我希望獲得二進制位置的百分比和mb中使用和空閑內存的值,就​​像這個“使用:2345.25”在這個問題中記得

希望你的建議

提前致謝

String.format()怎么樣?

System.out.println(String.format("output: %.2f", 123.456));

輸出:

output: 123.46

試試這樣吧

    double d = 1.234567;
    DecimalFormat df = new DecimalFormat("#.##");
    System.out.print(df.format(d));

使用DecimalFormat,我們可以格式化我們想要看到的方式。

您可以使用DecimalFormat打印到兩個小數位。 因此,要打印帶有兩位小數的x = 2345.2512 ,您可以編寫

NumberFormat f = new DecimalFormat("#.00");
System.out.println(f.format(x));

這將打印2345.25。

盡管可以使用NumberFormat及其子類DecimalFormat來解決此問題,但這些類提供了許多應用程序可能不需要的功能。

如果目標只是漂亮打印,我建議使用String類的format函數。 對於您的特定代碼,它看起來像這樣:

string.append(String.format("Memomry usage:total:%1.2f Mb-used:%1.2f Mb(%1.2f %%)-free:%1.2f Mb(%1.2f %%)",totalMemory/1024/1024,usageMemory/1024/1024,Percentage,freeMemory/1024/1024,Percentagefree));

如果您打算指定一個標准格式,其中表示所有數字,無論它們是從字符串解析還是格式化為字符串,我建議使用* Format類的單例。 它們允許您使用標准格式,也可以在方法之間傳遞格式描述。

希望能幫助您選擇在您的應用程序中使用的正確方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM