increment function

double increment(
  1. double value, [
  2. int count = 1
])

Increments a floating point number to the next bigger number representable by the data type.

The incrementation step length depends on the provided value. increment(double.maxFinite) will return positive infinity.

Implementation

double increment(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 (intValue < 0) {
    intValue -= count;
  } else {
    intValue += count;
  }

  // Note that int64MinValue has the same bit pattern as -0.0.
  if (intValue == int64MinValue) {
    return 0.0;
  }

  // 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);
}