.NET - Why is there no fixed point numeric data type in C#?

11.8k Views Asked by At

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.

3

There are 3 best solutions below

4
On BEST ANSWER

Decimal (base-10 floating point) was deemed to be good enough.

7
On

You're looking for the little-known System.Data.SqlTypes.SqlDecimal class.

2
On

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.