It seems like there would be a ton of uses for a fixed point data type. Why is there not one in .NET?
Note: I understand we can create our own classes/structs to sui
You're looking for the little-known System.Data.SqlTypes.SqlDecimal class.
Decimal (base-10 floating point) was deemed to be good enough.
One problem probably has to do with the question: where do you fix the point? A type in .NET cannot be parametrized by other arguments than types, so FixedNum<18,6>
is simply not possible. And you do not want to create FixedNum1x0
, FixedNum1x1
, FixedNum2x0
, FixedNum2x1
, FixedNum2x2
, etc.
You need to be able to parametrize your fixed point type, not just values, because that would lead to nigh impossible to track mistakes:
FixedNum f() { return new FixedNum(1, decimals: 2); }
FixedNum x = new FixedNum(1, decimals: 0);
...
x = f(); // precision of x increased.
So you'd need to check and constrain your fixed point values every time you get them from something that's not a local variable. As you do with decimal
when you want a fixed scale or precision.
In other words, given the limitations of the .NET type system, decimal
is already built-in implementation of the FixedNum class above.