This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The problem asks for me to list side by side how many pounds are in a kilogram from 1 to 199. I have everything right except all these random zeros pop up after each of the pounds. For example, 3 kilograms = 6.600000000000005 pounds. I have read on this else where, and everyone suggests using the decimal format, DecimalFormat("#,###.##"); , but unfortuantely i have not been taught that yet, so i can't use it. I was thinking of using the % operator..but still cant figure out how to do it.
Do you mean the printf method with the % tags. Try %.2f. there are more details in the "formatting" link on this page in the Java™ Tutorials, and also in the Formatter class, which is more comprehensive, but also difficult to read.
Nick Hallloran wrote:Can you explain how it works? Does it force it to be a double?
It's quite simple. When an operation is done, the result is of the higher range type. Hence, an int with an int is an int, a double with an int is a double, a float with an double is a double. etc. So, in this case...
The first thing that is done, is kilograms and 22, which is an int and an int, which yields an int as a result. Luckily, no precision is lost, and the int didn't overflow. The next is a cast, which results in a double. The 10 is also casted which results in a double. Finally, a division is done with two doubles which results in a double.
You can actually do this instead...
The first thing that is done, is kilograms and 22.0, which is an int and a double, which yields a double as a result. Next, a division is done with a double and an int which results in a double.
Also, since the multiply and divide has the same precedence, and goes left to right, you can also get rid of the parens...
[EDIT: After reading the questions, I think I may have implied (and answered) a different question. Sorry.]
After rereading the question... here is another attempt at the answer...
Nick Hallloran wrote:
now im just trying to understand it...Can you explain how it works? Does it force it to be a double?
The main reason is that the number 22 and 10 can be represented exactly. Furthermore, the act of multiplying by 22 then dividing by 10, loses less precision than multiplying by 2.2. Quite frankly, even this is not guaranteed to work. It may break if you want to expand to a bigger range, or convert to a different unit, etc. You will need to use one of the solutions mentioned so far, if you want to guarantee it.
Joined: Feb 09, 2010
OH ok i understand now....thank you very much for your help...keep watching this forum..because more than likely i may have another question pop up when i aget assigned another set of problems.