Results 1 to 10 of 10
Thread: Rounding calculations
- 08-20-2011, 01:26 PM #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.
However, this return 7.8443242 and i want it to return 8 (rounded value)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));
How do i do this please?
thanks
- 08-20-2011, 01:41 PM #2
Member
- Join Date
- Nov 2010
- Posts
- 15
- Rep Power
- 0
Hello Lynxbci, there is a round method in the java.lang.math library.
Fabrice
- 08-20-2011, 01:47 PM #3
Member
- Join Date
- Nov 2010
- Posts
- 15
- Rep Power
- 0
float test = (float) 2.45;
long testRound= Math.round(test);
this is how you use it.
- 08-20-2011, 01:55 PM #4
Member
- Join Date
- Aug 2011
- Posts
- 2
- Rep Power
- 0
Thanks very much all working ok
- 08-20-2011, 02:50 PM #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;
- 08-20-2011, 02:58 PM #6
Member
- Join Date
- Aug 2011
- Posts
- 11
- Rep Power
- 0
- 08-20-2011, 03:14 PM #7
Member
- Join Date
- Aug 2011
- Posts
- 4
- Rep Power
- 0
What about this:
double test = 7.82562;
int rounded = (int) (test + 0.5);
- 08-20-2011, 03:19 PM #8
Member
- Join Date
- Aug 2011
- Posts
- 11
- Rep Power
- 0
That works unless the number is negative.
- 08-20-2011, 03:32 PM #9
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
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.
-
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.
Similar Threads
-
update text output (eg. jLabel) during calculations
By kosmo76 in forum AWT / SwingReplies: 2Last Post: 04-06-2011, 10:30 PM -
Thread calculations, and another thread to use the calculations
By phil128 in forum Threads and SynchronizationReplies: 4Last Post: 12-12-2010, 04:32 PM -
[SOLVED] Simple Calculations in Java
By fullmetaljacket in forum New To JavaReplies: 9Last Post: 05-19-2009, 03:19 AM -
decimal calculations?
By arnab321 in forum CLDC and MIDPReplies: 5Last Post: 11-19-2008, 03:36 AM -
Need help rounding. =/
By yo1mcool in forum New To JavaReplies: 1Last Post: 10-07-2008, 05:02 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks