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

后端 未结 3 706
难免孤独
难免孤独 2021-01-11 17:20

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

3条回答
  •  执念已碎
    2021-01-11 17:49

    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.

提交回复
热议问题