canStore static method

bool canStore(
  1. double val, {
  2. required bool signed,
  3. required int integerWidth,
  4. required int fractionWidth,
  5. FloatingPointRoundingMode roundingMode = FloatingPointRoundingMode.truncate,
})

Return true if double val to be stored in FixedPointValue with integerWidth and fractionWidth lengths without overflowing.

Implementation

static bool canStore(double val,
    {required bool signed,
    required int integerWidth,
    required int fractionWidth,
    FloatingPointRoundingMode roundingMode =
        FloatingPointRoundingMode.truncate}) {
  if (!val.isFinite) {
    return false;
  }
  final exact =
      FloatingPoint64Value.populator().ofDouble(val).toScaledBigInt();
  if (!signed && exact.significand.isNegative) {
    return false;
  }
  final shift = exact.exponent + fractionWidth;
  final scaled = shift >= 0
      ? exact.significand << shift
      : roundBigIntByPowerOfTwo(exact.significand, -shift,
          roundingMode: roundingMode);
  final width = integerWidth + fractionWidth + (signed ? 1 : 0);
  if (width < 1) {
    return false;
  }
  final minValue = signed ? -(BigInt.one << (width - 1)) : BigInt.zero;
  final maxValue = signed
      ? (BigInt.one << (width - 1)) - BigInt.one
      : (BigInt.one << width) - BigInt.one;
  return scaled >= minValue && scaled <= maxValue;
}