C# gives you three real-number types and picking the wrong one gets expensive. decimal keeps exact base-10 values and is the one for money. double and float are binary floating point, which is fast and compact but cannot represent 0.1 exactly.
That is why 0.1 plus 0.2 does not equal 0.3 when you use a double, and why you should never compare two floating point values with the equality operator. There is an article below on how to compare them properly.
So: decimal for money and anything a human will check by hand, double for measurements and maths, float only when you have a lot of values and memory matters more than precision.
Everything below, from the type choice through to random number generation.
Choosing a Numeric Type
decimal, double or float, and how to tell the difference at runtime.
- Controlling Precision of Decimal Numbers
- Double vs Float vs Decimal
- SIMD Accelerated Numeric Types
- How to Check if an Object Is a Number
- Techniques for Checking Floating-Point Equality
Rounding and Precision
Controlling how a number is cut down, which matters more than it looks once money is involved.
Converting and Checking Numbers
Moving between number bases, and asking a number a question.
- Different Techniques to Convert a Number Between Hexadecimal and Decimal
- Hexagonal Architectural Pattern
- How to Check if a Number Is Positive or Negative
Random Numbers
The Random class, and the cryptographic generator you need instead of it when the value must not be guessable.
- Random Class
- Create Cryptographic Numbers With RandomNumberGenerator
- How to Generate Random Numbers From a Range
- Generate Random Double Numbers in a Range
- Fastest Way to Generate a Random Boolean
- How to Generate a Random Color Name
More Math
The Math class and everything else numeric.
Where to Go Next
Numbers usually arrive as text or leave as text:
The equality operator on two doubles is the thing to watch for in code review. It compiles, it passes the happy-path test, and it fails on the value a customer types in.
