
"What about the float type?" asked someone behind me.
A float is almost the same as a double. The main difference is that a double is twice as large as a float in memory space (hence the name 'double'). This results in a different range of values that you can store in these two types:
Type | Space in Memory | Approximate Range | Precision | Default Value | Example |
---|---|---|---|---|---|
float | 4 bytes | -3.4 x 10 38 to +3.4 x 10 38 | 7 | 0.0f | 0.1234567f |
double | 8 bytes | ±5.0 x 10 -324 to ±1.7 x 10 308 | 16 | 0.0 | 0.1234567890123456 |
By default, every real number in C# program is treated as a double. To force C# to recognize a number as a float, you must add an "f" at the end of every float, as shown in the above table and the below example.
You can add, subtract, multiply, and divide double and float variables the same as you can with doubles and ints. The result will again be a double type.
double someDouble = 1.5;
float someFloat = 2.5f;
double sum = someDouble + someFloat;
Console.WriteLine(sum); // Outputs 4
double subtract = someDouble - someFloat;
Console.WriteLine(subtract); // Outputs -1
double multiply = someDouble * someFloat;
Console.WriteLine(multiply); // Outputs 3.75
double divide = someDouble / someFloat;
Console.WriteLine(divide); // Outputs 0.6
After walking around to make sure we had grasped the new concepts, Ritchie returned to the front of the room. "From now on," he began, "we're going to use the double type because it's as fast as the float type, but provides much more precise results. I suggest that you all get comfortable using the double in your programs, and only use a float if you have a very good reason to do so."
"Let's wrap up the first part of our meeting," Ritche said. "Complete this next task and then take a half-hour lunch break. We'll get into more new types this afternoon!"
