Computer Science Canada Round to digits |
Author: | KillCloud [ Wed Oct 11, 2006 6:03 pm ] |
Post subject: | Round to digits |
Please tell me how to round a number to digits, like round 1.345666 to 2 digits, thus, 1.35. |
Author: | KillCloud [ Wed Oct 11, 2006 6:14 pm ] | ||
Post subject: | |||
Ok i know that
will round to 2 decimal place but i dont understand how it works can someone explain it? thx |
Author: | Andy [ Tue Oct 17, 2006 11:39 pm ] |
Post subject: | |
why not look it up on the [url=http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf(java.lang.String,%20java.lang.Object...)]java[/url] api? |
Author: | ericfourfour [ Thu Oct 19, 2006 10:44 pm ] | ||
Post subject: | |||
Or you can make your own method. Here;s how it could look.
I'm pretty sure that should work. |
Author: | zylum [ Fri Oct 20, 2006 12:00 am ] | ||
Post subject: | |||
you could do a little bit better:
*note this is untested but you get the point.. ei use the round() method rather than adding 0.5 and casting. also, if you are dealing with 2 ints and you are dividing and you want to keep decimal places, cast one of the ints to a double rather than multiply by 1.0 |
Author: | ericfourfour [ Fri Oct 20, 2006 4:31 pm ] | ||
Post subject: | |||
another improvement would be:
That one can use negatives to you could round to negative decimals. For example: num = round (127, -2) num would equal 100 (or 130 I can't think right now). |
Author: | ericfourfour [ Sun Oct 22, 2006 2:35 am ] | ||||
Post subject: | |||||
This one should work. I added 0.5 and casted to an integer because that way it isn't dependant on Math.round (using a separate rounding method for your rounding method doesn't make much sense). I also threw in a power method because the one in the Math class doesn't do negatives. This one has been tested and it works.
|
Author: | Ultrahex [ Sun Oct 22, 2006 10:15 pm ] |
Post subject: | |
Im Hoping You guys know that there is something called DECIMAL FORMATTING in java...... oh well lol |
Author: | Aziz [ Mon Oct 23, 2006 9:15 am ] | ||||
Post subject: | |||||
Guys, don't reinvent the wheel: Math.round() will return a long type rounded to the nearest 1. Math.pow(double x, double y) will return x^y To round to 2 decimal places...
Or, a simple function:
That way, you can round to the nearest hundred (so 155 will be 200) by specifying -3 as the 'places'. Or something like that. No time to test it out, I'm at school. |