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

和自甴很熟 提交于 2019-12-05 03:52:53

How about String.format()?

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

Output:

output: 123.46

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.

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.

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.

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