Ask your own question, for FREE!
Computer Science 17 Online
OpenStudy (richyw):

basic java question. rounding decimal.

OpenStudy (richyw):

alright so I have a program that is supposed to calculate the surface area of a cylinder. The exact answer to it for radius 2 and height 5 is \(28 \pi\). I want it to show \(28 \pi \text { not } 28.0\pi\) the problem I am having is sometimes it would have to show like \(24.5\pi\) and other times it might be a repeating decimal like \(24.3333333...\pi\). Is there a way to make it round only when appropriate?

OpenStudy (richyw):

because I know I can do Math.round, but that would mess up the 24.5 one. I want it to display no decimal place if it is exactly an integer number, and not to round if is not an integer number.

OpenStudy (anonymous):

Hey, So I'm not quite sure what you'd want to display in the case of 2.33...pi: is it 2.33pi or 2.33....pi? Because the latter might be a bit tricker :) But for the other examples you might want to take a look at the DecimalFormat class. API link: http://docs.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html Let me know if that works for you, Best,

OpenStudy (anonymous):

public class RoundTwoDecimalPlaces{ public static void main(String[] args) { float num = 2.954165f; float round = Round(num,2); System.out.println("Rounded data: " + round); } public static float Round(float Rval, int Rpl) { float p = (float)Math.pow(10,Rpl); Rval = Rval * p; float tmp = Math.round(Rval); return (float)tmp/p; } }

OpenStudy (rsmith6559):

Just for a different point of view, do you want the math value changed or is this a print formatting issue?

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!