formatNumberForClipboard function

String formatNumberForClipboard(
  1. num? value, {
  2. int maxFractionDigits = 2,
})

Formats a number for clipboard copying. Handles integers and floats, returning a string with appropriate decimal precision.

value is the number to format. Accepts a nullable num. If null, returns '0' to signify zero. This ensures output validity.

Outputs a String. Integers are formatted without decimals. Non-integers are formatted with a fixed decimal count, defaulting to two places. This can be adjusted using maxFractionDigits.

maxFractionDigits is an optional parameter for non-integer numbers. It sets the maximum decimal places, defaulting to 2. It's ignored for integers.

Returns: String of the formatted number. Integer numbers have no decimals. Non-integers include up to maxFractionDigits decimals for consistency.

Implementation

String formatNumberForClipboard(num? value, {int maxFractionDigits = 2}) {
  // Check if the provided value is null. If it is, default to '0'.
  if (value == null) return '0';

  // Determine if the value is a non-decimal number. If it is, format it
  // without any decimal places. Otherwise, ensure that it has two decimal
  // places to standardize the look of the output.
  final isInteger = isNumberInteger(
    value,
    epsilonExponent: maxFractionDigits,
  );

  return isInteger
      ? value.toStringAsFixed(0)
      : value.toStringAsFixed(maxFractionDigits);
}