Question:

Problem in Netbeans, Java Language?

by  |  earlier

0 LIKES UnLike

I'm trying to limit my answer to two decimal places only

but when i run the program i always get this kind of answer

for example-

answer=0.000000000000000000000

instead of

answer=0.00

and how do i round a decimal number

for example-

1.36 becomes 1.4, I'm using netbeans 6.1 and i need some help in programming

 Tags:

   Report

1 ANSWERS


  1. You can't, at least not with the number itself.  If it is a float, it is 32 bit.  If it is a double, it is 64 bit.  The answer is to produce a formatted String representation of your floating point number.

    You have two ways of doing this.  The "original" old standard way was to use a formatter from the java.text package.  In this case, you would use the NumberFormat class.

    double d = 234.2233322;

    NumberFormat nf = NumberFormat.getInstance();

    nf.setMaximumFractionDigits(2);

    System.out.println(nf.format(d));

    This will print out 234.22.  You can even set the rounding mode used by NumberFormat.

    The "newer" convenience method of also formatting String output is to use the Printstream method called printf().  Here, you have to specify the special "format string".

    System.out.printf("%1.2f \n", d);

    The % means replace this with the argument value.  The 1.2f means at least 1 digit before the decimal and 2 after (the "f" means a floating point decimal value).

    The NumberFormat approach is nice in that you have more control and since you get the String reference from the format() method, you can always convert your "rounded number" back into a float or double.

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.