# float to 2 decimal places

• November 25th, 2009, 08:26 AM
fh84
float to 2 decimal places
hello to all,
is there any easy way to convert a float to 2 decimal places?
all the examples on the net are too complicated

Code :

` f = f/99;`

this is all i want to do.

thank you!
• November 25th, 2009, 09:22 AM
helloworld922
Re: float to 2 decimal places
If you can guarantee that your number can fit inside an int (or a long), do this:

Code :

```long temp = 100.0 * f; f = temp/100.0;```

Or, in one line:

Code :

`f = ((long)(100.0*f))/100.0;`

edit: as a side question, why do you want to only have 2 decimal precision? It's generally advisable to have all the decimals in place, and then only display out to two decimals precision.

Code :

`System.out.printf("f is %f, which is %.2f with 2 decimals precision",f,f);`
• November 25th, 2009, 09:32 AM
fh84
Re: float to 2 decimal places
well this is the actual code:
Code :

```  double meanValue = 0; meanValue = meanValue + rndNumber; double mean = meanValue / 99; System.out.println("The Mean Value is :" + mean);```

the result appears as : 1.5555555555555556

is there any way to reduce to 2 decimal points?

the one above didn't really help!

thank you!
• November 25th, 2009, 10:27 AM
Json
Re: float to 2 decimal places
The thing is that float and double will never really only be two decimals, it all depends on the precision of the operating system.

However if you wish to print the float/double value with only two decimals then you can use the method a couple of posts above.

Code :

`System.out.printf("The Mean Value is : %.2f", mean);`

Have a look at Formatter (Java Platform SE 6) for more information on how to print using formatter.

// Json