decrement function

double decrement (double value, [ int count = 1 ])

Decrements a floating point number to the next smaller number representable by the data type.

The decrementation step length depends on the provided value. decrement(double.MinValue) will return negative infinity.

Implementation

double decrement(double value, [int count = 1]) {
  if (value.isInfinite || value.isNaN || count == 0) {
    return value;
  }

  if (count < 0) {
    return decrement(value, -count);
  }

  // Translate the bit pattern of the double to an integer.
  // Note that this leads to:
  // double > 0 --> long > 0, growing as the double value grows
  // double < 0 --> long < 0, increasing in absolute magnitude as the double
  //                          gets closer to zero!
  //                          i.e. 0 - epsilon will give the largest long value!
  var bytes = ByteData(8);
  bytes.setFloat64(0, value);
  int intValue = bytes.getInt64(0);

  // If the value is zero then we'd really like the value to be -0. So we'll make it -0
  // and then everything else should work out.
  if (intValue == 0) {
    // Note that long.MinValue has the same bit pattern as -0.0.
    intValue = int64MinValue;
  }

  if (intValue < 0) {
    intValue += count;
  } else {
    intValue -= count;
  }

  // Note that not all long values can be translated into double values. There's a whole bunch of them
  // which return weird values like infinity and NaN
  bytes.setInt64(0, intValue);
  return bytes.getFloat64(0);
}