Alex Rivera | Logout

Does C# have an Unsigned Double?

Asked 2011-09-05T08:53:02.927
46

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

Does anyone know why?

Edit
Report

2 Answers

23

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
}
answered 2011-09-05T09:06:25.243
3

There is no such thing as an unsigned double in any language or system that I have ever heard of.

I need to give the ability to pass a variable that can be a fraction and must be positive. I wanted to use it in my Function signature to enforce it.

If you want to enforce a constraint that the parameter is positive, then you need to do that with a runtime check.

answered 2011-09-05T08:58:28.837

Your Answer