Dear Friends Math.round() behaves diffrently with -ive nos e.g 1. Math.round(3.5) ------> 4 2. Math.round(-3.5) ------> -3 3. Math.round(-3.51) ------> -4 what is the funda behind that. If it gives the round off no then -3.5 should give -4 not -3 thanks Naveen
Well, when the digit left of the decimal point is greater or equal to 5, the floating number is rounded to the next greater integer. For instance, Math.round(3.5) will return 4. Similarly, with negative floating numbers, such as -3.5, Math.round(-3.5) will return the next greater integer, which is -3.
Dear Camroon You are ok whatever u have said but the problem is still there that why Math.round(-3.51) gives -4 but Math.round(-3.5) gives -3 Problem still arises Naveen
Naveen As far as I know 'round()' works as follows: Step 1. Add 0.5 Step 2. Calculate floor() of result Step 3. Cast to int or long depending on whether original number was float or long. So your two examples will be round(-3.5) -> -3.5 + 0.5 -> -3.0 -> floor of -3.0 is -3.0 which when cast to a long is -3 round(-3.51) -> -3.51 + 0.5 -> -3.1 -> floor of -3.1 is -4.0 which when cast to a long is -4. round results in an int for a float and a long for a double. Hope this helps. Siobh�n
Thanks siobhan calculation of round() in this way is really new to me.Now the concept is totally clear. Will you please tell me where did u find these steps to calculate the round of a number because i have never found out this in khalid mughal and phillip heller..... may be i would be missing lot of things like this thanks again Naveen
Naveen I learnt this from Velmurugan's notes. Velmurugan's complete and concise study notes only (no questions) are available at the following. You have to download a MS Word document. http://www.geocities.com/velmurugan_p/notes.html
Hi Naveen, The explanation is in the JDK API. It is a good idea to always check the documentation when you are trying to understand a class or method. Hope that helps. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform