Glossary / decimal versus floating point
decimal versus floating point
C# decimal uses base-10 scaling with high decimal precision, while float and double use IEEE 754 binary floating-point. Binary floating-point is fast and has a wide range but cannot exactly represent many decimal fractions; decimal is suited to financial quantities where base-10 rounding behavior matters, but has a narrower range and different performance characteristics.
Precision and operations
double a = 0.1 + 0.2; // approximately 0.30000000000000004
decimal price = 0.1m + 0.2m; // 0.3
Use m suffix for decimal literals; without it, literals such as 0.1 are double. Decimal arithmetic rounds according to decimal representation and operations, but does not eliminate domain rounding policy: money still needs an explicit scale, rounding mode, and treatment of tax/currency. Floating-point comparisons often need tolerances based on magnitude and error analysis rather than exact equality.
double is typically preferred for scientific, statistical, graphics, and general numerical work. float is useful where memory/bandwidth or hardware/API formats require 32-bit precision. Decimal operations may be slower and decimal cannot represent infinities/NaN in the same way as IEEE floating point.
Engineering guidance
Choose representation from domain requirements and interoperability. Avoid mixing numeric types implicitly; conversions can lose precision or overflow. Test boundary and rounding cases, specify MidpointRounding policy, and use integer minor units where suitable for currency with fixed scale.
Interview questions
- Why does 0.1 + 0.2 differ in double? These decimal fractions have no exact finite binary representation.
- When use decimal? Base-10 financial/business arithmetic with explicit rounding rules.
- Is decimal universally more accurate? No; it suits decimal fractions but has different range, precision, and performance tradeoffs.
- How compare doubles? With a tolerance justified by scale/error analysis.
- Why use integer cents? It can make fixed-scale monetary arithmetic exact, provided overflow and currency scale are managed.