Earlier we talked about issues with storing things, like a phone number as a number, due to overflow and accuracy issues.
So, we’re going to institute a general rule of programming. Only store something in a number when you are planning to, or could, perform mathematical operations on that number.
So for example, you have a series of prices for items in a store. As a programmer, you might need to calculate the average price of an item in the store, or add up a series of prices for a checkout, so you are performing a mathematical operation, and thus should store those numbers as a numeric data – most likely a float.
subTotal = 0
for item in shoppingCart:
subTotal += item.price
If you ask for a person’s age, you will probably want to store that as a number. Now, it’s rare that you would need to add, average, or multiple a collection of ages, so you might think it should be stored as a string. However, you might need to see if a person is over, or under, a given age. While you can perform greater than and less than operations on text, numeric data is both better suited for it, and less prone to errors.
if( age > 21 ) {
// you can now do _____
}
The problem with using numbers as strings
Consider for example the following which is true as a string, but false as a number.
"123" < "23" // true
123 < 23 // false
This is why it is so important to use a numeric data types if you are working with mathematical purposes. Even in so called type-less languages like Python and JavaScript, there is an internally used data type. Hysterical results, or run-time errors, will occur if you try to mix the two.
#python
print( 12 + "34")
// JavaScript
console.out( 12 + "34")
That is why even with type-less languages, you often find ways to convert between numbers and strings and vice-versa.
Using a string as a number
So when should you use a string to store a number?
Many common “numbers” there will never be a need to perform a mathematical operations on them, nor evaluate them as a number. These common numbers are best stored as a string. Consider the following data types which don’t need a type – as they can use strings:
- Zip/Postal Code
- Phone Number
- Social Security Number
- Employee ID / Employee Badge Number
There are of course many more out there, and one of the challenges is knowing when to use it. Ironically, the fact that many of them have the word “number” in part of the name of that value, means that it can be confusing for many new developers.
So always ask yourself, how is this data being used? In a numerical fashion, or not? Will it fit within the range of a number given a potential data size?
When Should a Number Not Be a Number was originally found on Access 2 Learn