问题
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 suit our fixed point purposes and needs. That's not my question. I want to know WHY MS decided not to include a fixed point numeric data type.
回答1:
Decimal (base-10 floating point) was deemed to be good enough.
回答2:
You're looking for the little-known System.Data.SqlTypes.SqlDecimal class.
回答3:
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.
来源:https://stackoverflow.com/questions/5069750/net-why-is-there-no-fixed-point-numeric-data-type-in-c