Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Integer with 2 decimal places in Java

in my code i use integers multiplied by 100 as decimals (0.1 is 10 etc). Can you help me to format output to show it as decimal?

like image 403
user1749458 Avatar asked Oct 20 '12 16:10

user1749458


People also ask

How do you print an integer with two decimal places?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.

What is .2f in Java?

printf("%. 2f", value); The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (.

Can int in Java have decimals?

Numbers are so important in Java that six of the eight primitive data types are numeric types. There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do.

How do you set decimal places in Java?

Using the format() method "%. 2f" denotes 2 decimal places, "%. 3f" denotes 3 decimal places, and so on.


1 Answers

int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));
like image 69
Juvanis Avatar answered Oct 14 '22 19:10

Juvanis