# Rounding calculations

• 08-20-2011, 02:26 PM
lynxbci
Rounding calculations
Hi,

I have a formula that peforms a calculation, and as the inputs are double, the calc is too.
Code:

```private double calcpoints(float input_pr, float input_ca, float input_fa, float input_fi) {                 return ((input_pr / 10.9) + (input_ca / 9.2) + (input_fa / 3.9) + (input_fi / 35));```
However, this return 7.8443242 and i want it to return 8 (rounded value)
How do i do this please?

thanks
• 08-20-2011, 02:41 PM
Fabken
Hello Lynxbci, there is a round method in the java.lang.math library.

Fabrice
• 08-20-2011, 02:47 PM
Fabken
float test = (float) 2.45;
long testRound= Math.round(test);

this is how you use it.
• 08-20-2011, 02:55 PM
lynxbci
Thanks very much all working ok
• 08-20-2011, 03:50 PM
RPFeltz
Perhaps converting it to an int value works too.
double test = 7.82562;
int rounded = (int) test;
• 08-20-2011, 03:58 PM
R-J
Quote:

Originally Posted by RPFeltz
Perhaps converting it to an int value works too.
double test = 7.82562;
int rounded = (int) test;

That will round everything between a 7 and an 8 to a 7.
• 08-20-2011, 04:14 PM
RPFeltz
double test = 7.82562;
int rounded = (int) (test + 0.5);
• 08-20-2011, 04:19 PM
R-J
That works unless the number is negative.
• 08-20-2011, 04:32 PM
sunde887
In general it's better to use what the libraries provide for you. Casting to an integer simply truncates the decimal portion. Like rj said, if x is -.6 and you did (int)(x+.5) you will still get 0.
• 08-20-2011, 04:49 PM
Fubarable
Or perhaps better would be to not round at all, but format the output into a nicely formatted and rounded String representation when this is needed. This can easily be done with a DecimalFormat object or String.format(...) method call.