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

若如初见. 提交于 2020-01-02 02:19:33

问题


hi i am trying to print after dividing in string builder and printing that string builder let show me my code ,

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

in above code "totalmemory" and "freememory" is of double type having bytes value in point not null so i divide it by "1024" two times to get it in "Mb" and "string" is variable of string builder after using this code i am simply printing it a am getting result as shown below,

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

i want to get percentage in twodecimal place and values of used and free memory in mb like this "used:2345.25" in this pattren remember

Hopes for your suggestions

Thanks in Advance


回答1:


How about String.format()?

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

Output:

output: 123.46



回答2:


Try like this

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

Using DecimalFormat, we can format the way we wanted to see.




回答3:


You can use DecimalFormat to print out to two decimal places. So, to print x = 2345.2512 with two decimal places, you would write

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

which will print 2345.25.




回答4:


Even though it is possible to use NumberFormat and it's subclass DecimalFormat for this issue, these classes provide a lot of functionality that may not be required for your application.

If the objective is just pretty printing, I would recommend using the format function of the String class. For your specific code it would look like this:

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));

If you are intending to specify a standard format in which all numbers are represented irrespective of whether they are being parsed from strings or formatted to strings, then I would recommend using singletons of the *Format classes. They allow you to use standard formats and also to pass format descriptions between methods.

Hope that helps you select the right method to use in your application.



来源:https://stackoverflow.com/questions/9528904/how-to-print-upto-two-decimal-places-in-java-using-string-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!