# Limiting decimal places in a double

• March 13th, 2010, 05:04 PM
darek9576
Limiting decimal places in a double
When i write in my program

double pi = Math.PI;

This will give me a value of PI accurate to many decimal places, but what if i want to limit this number
lets say to 3 decimal places..
Is there such a method in Java?

(Im not talking here only about the value of Math.PI or Math.E, but about all double values that contain
many decimal places)
• March 13th, 2010, 11:28 PM
andaji
Re: Limiting decimal places in a double
yes... to show the output into 3 decimal place.. you have to use..

System.out.printf ("%.3f" , Math.PI);

This will convert the output into 3 decimal places. In other output system like System.out.print or System.out.println you cannot format the output, but in System.out.printf(); you can format the output as like this problem.
Now if you want to change the output for example into 2 decimal place.... then you will use
("%.2f", Math.PI); rather than ("%.3f" , Math.PI).....

Whatever number you put after the %. sign..( it's the remainder sign & fullstop just after the % sign) and the type like decimal or floating or double value..for integer you put %d and for floating and double you put (%.f) .
if the value is floating or double value then you will have to use (%.2f) but if its an ineger value then you will have to use (%d) { no full stop after the % sign for an integer value )} rather than (%.f){ full stop after % sign if its double for floating numer}

then output into that much decimal place... now if you choose to 5 decimal place then you will have to put ("%.5f" , Math.PI);
now you don't have to use the System.out.printf to format the output.. i just showed this to tell the difference of System.out.print or println with System.out.printf (); method to show the output..

you can use this (%.2f" to any case, it will just format the decimal number into whatever number you put after the ("%. f" , Math.PI) sign.

• March 14th, 2010, 11:27 AM
copeg
Re: Limiting decimal places in a double
You can use the DecimalFormat object at described in the following link:
Double Formatting