I’m working on some small projects and don’t fully understand data types and their uses. Here are some things I’m wrestling with.
What data type would I use to represent:
- a person’s salary?
- a person’s date of birth?
- a person’s name?
- a person’s Social Security Number?
- the number of dependents a person is going to claim on their taxes?
- the weight of the Earth?
Are there any rock solid resources for data types?
Decimal.DateTime.String.String.floatordouble.Explanation
Money
It also can’t be an integer because you’ll need a decimal point ($59.9) and integers cannot have one, you’d have to convert it, e.g. with a cast which will always round it up for you:
((int)7.001) == 8istrue.You won’t use a string either. Text is just the wrong representation (quantifying money does not result in a list of characters, right?). And you’d also like to run some math, I’m sure, and you cannot do that with strings directly because it’s not numeric. E.g.
2 + 2 = 4. Try the same with strings:"2" + "2" = "22"(+is overloaded: it adds for numerics and concatenates for strings).Edit: My opinion of this has changed!.
Computers and floating points are notoriously complicated and even error-prone (if you do not know precisely what you’re doing). I suggest to not use them for money or anything precise & critical.
I recommend to use an integer type that will not overflow (for arbitrary size use
BigInteger) and use it to represent the lowest resolution you need. E.g. you’re likely to be okay with representing dollars as cents, so150is how you would represent1.5. Away with rounding errors and scary IEEE standards! woohoo! plus computers are faster with integers so you would typically get better performance, especially if you can manage to use anint, i.e. you’re certain it will not overflow.Phone Numbers & Security Number
Phone numbers and security numbers are called numbers, but really they’re just a string of digits, aren’t they? at least that seems the common perception. Well that already tells you: use a string.
You’re also unlikely to use a phone number for mathematical operations? (although I do suppose summing up phone numbers would make one wild afternoon).
Birthday
DateTimeis the standard .NET type for dates, I’m sure there’s no need to explain why, the name is self-explanatory.Name
String for obvious reasons.
Weight
doubleorfloatare used to this kind of things.It depends on how much precision you want. Double gives you more, but the trade-off is that it takes more memory. It only makes a real difference when you have tons of them. My rule of thumb is to go with doubles unless I actually need to use a single/float. That being said, from my experience, almost every game that has something like that (a gravity force value, a weight, and such) is usually a
floatand rarely adouble. Sometimes the domain will give you a different rule of thumb while you’re working in it.Differences between float & double: link & another link.