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
f = f/99;
this is all i want to do.
thank you!
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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
f = f/99;
this is all i want to do.
thank you!
If you can guarantee that your number can fit inside an int (or a long), do this:
long temp = 100.0 * f; f = temp/100.0;
Or, in one line:
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.
System.out.printf("f is %f, which is %.2f with 2 decimals precision",f,f);
Last edited by helloworld922; November 25th, 2009 at 10:26 AM.
well this is the actual 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!
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.
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
fh84 (November 25th, 2009)