functionJsonNumber function

String functionJsonNumber(
  1. num value
)

A finite number as JSON.stringify writes it. The strict parser keeps an integral value beyond 2^53 as a double, which jsonEncode would print with a trailing .0: below 1e21 an integral double is written as its shortest integer decimal, and negative zero as 0. Every other finite number already matches: both languages print the shortest round-trip decimal, in exponent form from 1e21 and below 1e-6.

Implementation

String functionJsonNumber(num value) {
  if (!value.isFinite) {
    throw const FormatException('Value is not finite scalar JSON.');
  }
  if (value == 0) return '0';
  if (value is double &&
      value == value.truncateToDouble() &&
      value.abs() < 1e21) {
    final text = value.toString();
    return text.endsWith('.0') ? text.substring(0, text.length - 2) : text;
  }
  return value.toString();
}