How to print up to two decimal places in java using line builder?

Hi, I'm trying to print after dividing in a string builder and printing this string constructor to 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 the above code, “totalmemory” and “freememory” is of double type, the byte value at the point is not null, so I divide it by “1024” twice to get it in “Mb”, and “string” is a string builder variable after using this code, I just print it, getting the 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 the percentage in a two-dimensional place and the values ​​of used and free memory in mb, as this "used: 2345.25" is remembered in this patent

We hope for your suggestions.

Thanks at Advance

+8
java stringbuilder jsp
source share
4 answers

What about String.format() ?

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

Output:

 output: 123.46 
+12
source share

try it

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

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

+2
source share

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

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

which will print 2345.25.

+1
source share

Although you can use NumberFormat and a subclass of DecimalFormat for this problem, these classes provide many functions that might not be needed for your application.

If the goal is a pretty pretty print, I would recommend using the String class format function. For your specific code, it will 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 intend to specify a standard format in which all numbers are represented, regardless of whether they are parsed from strings or formatted in strings, I would recommend using singletones of the * Format classes. They allow you to use standard formats, as well as transfer format descriptions between methods.

Hope you can choose the right method to use in your application.

+1
source share

All Articles