Read a Percentage Value

Here’s a thought experiment for you: How can you prompt a user to properly input a percentage value?

Mathematically, a percentage is a real number, ranging from 0.00 to 1.00 for 0% to 100%. So a value of 50% is really 0.50. How can you get the user to input 0.5 instead of 50%? Further, how can your input deal with 50%, which is a string?

Coddling users into providing proper input is an artform. You can write a lot of text at the prompt, explaining how input works and providing examples, but my experience shows that few users read that stuff. Instead, they plow ahead and fill in the blanks.

In a program that prompts for a percentage input — say, a tax rate, interest rate, depreciation, and so on — how can you assure that your code is manipulating the proper values?

The answer is to write a defensive input routine: Prompt the user for a percentage value input. Massage the text to ensure that the % character is ignored as well as any thousands separators. Display the result as a float value, the percentage.

Here is a test run of my solution:

Enter a percentage: 25
I'm working with a value of 25.00 percent

Enter a percentage: 500%
I'm working with a value of 500.00 percent

Enter a percentage: .06
I'm working with a value of 0.06 percent

Enter a percentage: 6,500%
I'm working with a value of 6500.00 percent

Your assignment this month is to write code that defensively processes text input and generates a percentage output. Don’t assume that the user is going to input a decimal value as a percentage; the string 25 evaluates to 25% (.25), as shown in the sample output above. Properly cull out any percent characters ('%') or thousands separators (',') in the input stream.

Click here to read my solution. As usual, please try this exercise on your own before you peek at what I’ve done.

Leave a Reply