Skip to content

[API Proposal]: Implement decimal floating-point types that conform to the IEEE 754 standard. #69777

Closed
@KTSnowy

Description

@KTSnowy

Background and motivation

While reading the documentation I noticed that the decimal type implemented in C# and .NET does not conform to the IEEE standard and appears to use it's own format, which can potentially cause issues and limitations in cases where using IEEE conforming decimal floating-point arithmetic are a must (Banks and financial systems).

Extending the current Decimal type with Decimal32, Decimal64 and Decimal128 types as specified in the IEEE standard could make C# and .NET more compatible with banking and financial systems.

It would also make C# one of the few languages that have these decimal types built-in instead of requiring big and complex third-party libraries for decimal floating-point arithmetic.

API Proposal

public readonly struct Decimal128 : 
IComparable, IComparable<decimal128>, 
IConvertible, IEquatable<decimal128>, 
ISpanFormattable, 
System.Runtime.Serialization.IDeserializationCallback, 
System.Runtime.Serialization.ISerializable;

API Usage

/// <summary>
/// Keeping my fortune in Decimals to avoid the round-off errors.
/// Example adapted from .net documentation.
/// </summary>
class PiggyBank {
    // Type can be decimal (original), decimal32, decimal64 or decimal128 (IEEE standard)
    protected decimal128 MyFortune;

    public void AddPenny() {
        MyFortune = Decimal.Add(MyFortune, .01m);
    }

    public decimal Capacity {
        get {
            return Decimal.MaxValue;
        }
    }

    public decimal Dollars {
        get {
            return Decimal.Floor(MyFortune);
        }
    }

    public decimal Cents {
        get {
            return Decimal.Subtract(MyFortune, Decimal.Floor(MyFortune));
        }
    }

    public override string ToString() {
        return MyFortune.ToString("C")+" in piggy bank";
    }
}

Alternative Designs

Alternatively, instead of providing new decimal types, change the current implementation to conform to the IEEE standard. This is a risky alternative though as it could potentially break backwards compatibility of apps that rely on the old implemention.

Risks

There shouldn't be any risks of adding new alternative decimal types (decimal32, decimal64 amd decimal128) since the original type will be unchanged and use of them would be "opt-in" by manually changing source code to use the new types.

Changing the current implementation of the decimal type instead would most likely be risky as there could be a number of different apps relying on that particular implementation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions