Computer Science Canada Rounding Decimal Numbers?

 Author: Delta [ Thu Jul 01, 2004 1:43 pm ] Post subject: Rounding Decimal Numbers? How do you round to decimal places? for example how do I round 8.49999999 to 8.5 Please explain. Thank you.

Author:  Paul [ Thu Jul 01, 2004 2:16 pm ]
Post subject:

isn't it Math.round?
like
 code: System.out.println(x + " is approximately " + Math.round(x));

 Author: Tony [ Thu Jul 01, 2004 2:53 pm ] Post subject: no, Math.round would round to an integer. What you do is you multiply it by 10^number of decimal places, round, and then divide back. such as 8.499 *10^1 84.99 ~ round 85 /10^1 8.5

 Author: Delta [ Thu Jul 01, 2004 3:28 pm ] Post subject: That's the thing tony... I asked how to round...

 Author: Tony [ Thu Jul 01, 2004 3:30 pm ] Post subject: i donno... you can typecast it to an (int) Author: wtd [ Thu Jul 01, 2004 4:13 pm ] Post subject: Do you just need this for formatting text?

Author:  zylum [ Fri Jul 02, 2004 1:10 pm ]
Post subject:

tony wrote:
no, Math.round would round to an integer. What you do is you multiply it by 10^number of decimal places, round, and then divide back.

such as
8.499 *10^1
84.99 ~ round
85 /10^1
8.5

i think tony's way is the only way to do it unless there is some weird function i havent heard of...

 code: double num = 8.4999; num *= 10; num = Math.round(num); num /= 10; // or just num = Math.round(num * 10) / 10; System.out.println(num); // gets you 8.5

 Author: Dan [ Fri Jul 02, 2004 2:12 pm ] Post subject: Thats how i do it also. Alougth u whould think there whould be a method for it some where in one of thous java APIs.

 Author: LiquidDragon [ Fri Jul 09, 2004 7:26 pm ] Post subject: I always thought there was a round method. But i may be wrong Author: zylum [ Fri Jul 09, 2004 11:42 pm ] Post subject: there is a round method but it rounds to the nearest one not the nearest tenth.

Author:  Delta [ Sat Jul 24, 2004 8:13 am ]
Post subject:

Ok well I found some nice lil rounding methods... (I believe this was just for rounding so I could display the text)

 code: import java.text.*; DecimalFormat decF = new DecimalFormat ("###.##"); System.out.println (decF (99999.999999));

also

 code: decF.setMinimumFractionDigits(2);

would set the format to a minimum of two decimal places

 code: decF.setMaximumFractionDigits(2);

would set the format to a maximum of two decimal places

The decimal format thing is only for text as far as I know (for outting it)...

but when it came to storing the value I usually ended up using 'long' instead of 'int' or 'double'... because long would actually round how I wanted it to... never the less... thanks for the help.... Have a nice day.

 :