I am getting input from the user and it needs to be either a whole number or some multiple of 0.5.
For example, 7, 23 and 5.5 are all valid but 3.1 and 2.7 are not.
In other words, if the user keys in 2.3, there will be an alert telling them that they can only key in 2.5.
How do I go about performing this validation?
Since they’re entering strings, and floating point numbers are notoriously difficult to get right 🙂 I would suggest checking the string input itself, before conversion to a float.
If it contains the
.character, make sure the last two characters are.5.You may want to check other cases as well depending on what you want to allow. For example,
7.0may be valid as may2.50000000.But, for simplicity, I’d simply state that the input has to either be a whole number, or end with
.5.