Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 377
Syed Raza Avatar asked Mar 02 '12 06:03

Syed Raza


People also ask

How do you correct to 2 decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

What is 2f in Java?

2f syntax tells Java to return your variable ( val ) with 2 decimal places ( . 2 ) in decimal representation of a floating-point number ( f ) from the start of the format specifier ( % ). There are other conversion characters you can use besides f : d : decimal integer.

How do you correct decimal places in Java?

We can use format() method of String class to format the decimal number to some specific format.

What is round to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.


2 Answers

How about String.format()?

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

Output:

output: 123.46
like image 68
Manish Avatar answered Oct 02 '22 12:10

Manish


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.

like image 26
Jayy Avatar answered Oct 02 '22 11:10

Jayy