How to I disply only 3 numbers after dot of double?

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
barakmitz
New poster
Posts: 1
Joined: Sat Nov 22, 2008 12:06 pm

How to I disply only 3 numbers after dot of double?

Post by barakmitz »

Hi,
I want to sidply Double variables but I want it always to be 3 numbers after the dot
Example:
4 ---> 4.000
1642.63787565 ----> 1642.638

and so on
how can i do this?
I heard something about printf but im not sure how to use it or if it works...

Thanks
mf
Guru
Posts: 1244
Joined: Mon Feb 28, 2005 4:51 am
Location: Zürich, Switzerland
Contact:

Re: How to I disply only 3 numbers after dot of double?

Post by mf »

System.out.printf("%.3f\n", Math.PI);
cjrr2046
New poster
Posts: 4
Joined: Sun Dec 28, 2008 8:39 pm

Re: How to I disply only 3 numbers after dot of double?

Post by cjrr2046 »

double a1=2.02356323; // Any double //
DecimalFormat df=new DecimalFormat ("0.000");
String a2=df.format (a1);
System.out.println (a2);

DecimalFormat is in this package: java.text.DecimalFormat;
jpaul
New poster
Posts: 2
Joined: Sat May 02, 2009 6:28 am

To format a double...

Post by jpaul »

Hi!
You can use DecimalFormat for create someone format for the floating point numbers, as double, but you don't need that... You should use the next form for print data, I test that is the faster form for print data in Java.

Code: Select all

PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
// use for all output

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

// use to endish
out.flush();
Post Reply

Return to “Java”