Rounding Program

Overview:  Let’s say you write a program that divides $5.00 between three people.  If you use appropriate data types, you program would probably display 1.66667.  Many times, we don’t want to display this many decimal places, especially with money.  Your task is to use what we currently know to make this number into a more money-friendly number (2 decimal places).

Assignment:  Write a program that allows a user to enter a float.  The program then truncates everything after the 2nd decimal digit (hundredths place).

Input:  Enter a number:  43.555555

Output: 43.55

Algorithm:  This involves using the idea that INTEGERS truncate remainder (decimal) digits. 

1.       If you take a float number (like 43.555555) and CRAM it into an integer (or short…etc), the floating part will be lost. 

2.       However, in this case, we want to keep the first two digits after the decimal…we can’t just chop them off. 

3.       Before chopping begins, you can multiply your float number by 100.  (43.555555 * 100 = 4355.5555).  This keeps the two fives that we want, but they’re on the wrong side of the decimal.

4.       Now, you can cram the float into an integer and lose the decimal places.  This should give you 4355 instead of 4355.5555. 

5.       If you take your new integer and put it back into a float, you regain the use of decimal places.  (4355 becomes 4355.000000).

6.       Next, you can divide you new float by 100 (un-doing what you did earlier when you multiplied by 100).  4355.0000 becomes 43.55.  Viola!

Extension:  If you get your program to work for 2 decimal places, try to allow the user to enter the number of decimal places to round.  If the user enters 3 places, show their number with three decimal places.  (Hint:  Use 10^3 for 3 places.  10^3 = 1000.)