javaParseDouble function
Java Double.parseDouble: trims characters <= ' ', accepts an
optional sign, NaN, Infinity, decimal and exponent notation, a
trailing f/F/d/D, and hexadecimal floating point. Returns null
where Java throws NumberFormatException.
Implementation
double? javaParseDouble(String input) {
final s = javaTrim(input);
final decimal = _javaDecimal.firstMatch(s);
if (decimal != null) {
final negative = decimal.group(1) == '-';
final value = switch (decimal.group(2)!) {
'NaN' => double.nan,
'Infinity' => double.infinity,
// Dart rejects a trailing '.', so append a zero ("1." -> "1.0").
_ => double.parse(
decimal.group(4)!.replaceFirst(_trailingPoint, '.0') +
(decimal.group(5) ?? ''),
),
};
return negative ? -value : value;
}
final hex = _javaHex.firstMatch(s);
if (hex != null) {
final intPart = hex.group(2)!;
final fracPart = hex.group(3)!;
if (intPart.isEmpty && fracPart.isEmpty) return null;
final mantissa = BigInt.parse(
'0$intPart$fracPart'.replaceFirst(_leadingZeros, ''),
radix: 16,
);
final exponent = int.parse(hex.group(4)!) - 4 * fracPart.length;
var value = mantissa.toDouble();
value = exponent >= 0 ? value * _pow2(exponent) : value / _pow2(-exponent);
return hex.group(1) == '-' ? -value : value;
}
return null;
}