1. Member
Join Date
Aug 2011
Posts
2
Rep Power
0

## Rounding calculations

Hi,

I have a formula that peforms a calculation, and as the inputs are double, the calc is too.
Java 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

2. Member
Join Date
Nov 2010
Posts
18
Rep Power
0
Hello Lynxbci, there is a round method in the java.lang.math library.

Fabrice

3. Member
Join Date
Nov 2010
Posts
18
Rep Power
0
float test = (float) 2.45;
long testRound= Math.round(test);

this is how you use it.

4. Member
Join Date
Aug 2011
Posts
2
Rep Power
0
Thanks very much all working ok

5. Member
Join Date
Aug 2011
Posts
4
Rep Power
0
Perhaps converting it to an int value works too.
double test = 7.82562;
int rounded = (int) test;

6. Member
Join Date
Aug 2011
Posts
11
Rep Power
0
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.

7. Member
Join Date
Aug 2011
Posts
4
Rep Power
0
double test = 7.82562;
int rounded = (int) (test + 0.5);

8. Member
Join Date
Aug 2011
Posts
11
Rep Power
0
That works unless the number is negative.

9. 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.

10. 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•