Does C# have an Unsigned Double?

后端 未结 4 677
忘掉有多难
忘掉有多难 2020-12-20 11:14

I need to use an unsigned double but it turns out C# does not provide such a type.

Does anyone know why?

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 11:28

    As pointed out by Anders Forsgren, there is no unsigned doubles in the IEEE spec (and therefore not in C#).

    You can always get the positive value by calling Math.Abs() and you could wrap a double in a struct and enforce the constraint there:

    public struct PositiveDouble 
    {
          private double _value;
          public PositiveDouble() {}
          public PositiveDouble(double val) 
          {
              // or truncate/take Abs value automatically?
              if (val < 0)
                  throw new ArgumentException("Value needs to be positive");
              _value = val;
          }
    
          // This conversion is safe, we can make it implicit
          public static implicit operator double(PositiveDouble d)
          {
              return d._value;
          }
          // This conversion is not always safe, so we make it explicit
          public static explicit operator PositiveDouble(double d)
          {
              // or truncate/take Abs value automatically?
              if (d < 0)
                  throw new ArgumentOutOfRangeException("Only positive values allowed");
              return new PositiveDouble(d);
          }
          // add more cast operators if needed
    }
    

提交回复
热议问题