1use std::fmt::Write as _;
6
7#[must_use]
24pub fn py_float_repr(x: f64) -> String {
25 if x.is_nan() {
26 return "nan".to_owned();
27 }
28 if x.is_infinite() {
29 return if x > 0.0 { "inf" } else { "-inf" }.to_owned();
30 }
31 let mut sci = format!("{x:e}");
33 let len = sci
34 .split('e')
35 .next()
36 .map_or(0, |m| m.bytes().filter(u8::is_ascii_digit).count());
37 if len > 1 {
38 let nearest = format!("{:.*e}", len - 1, x);
39 if nearest.parse::<f64>() == Ok(x) {
40 sci = nearest;
41 }
42 }
43 let (mant, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
44 let exp: i32 = exp.parse().unwrap_or(0);
45 let (neg, mant) = mant.strip_prefix('-').map_or((false, mant), |m| (true, m));
46 let digits: String = mant.chars().filter(char::is_ascii_digit).collect();
47 let mut out = String::new();
48 if neg {
49 out.push('-');
50 }
51 if (-4..16).contains(&exp) {
52 let point = exp + 1; if point <= 0 {
54 out.push_str("0.");
55 for _ in 0..-point {
56 out.push('0');
57 }
58 out.push_str(&digits);
59 } else {
60 let p = usize::try_from(point).unwrap_or(0);
61 if digits.len() <= p {
62 out.push_str(&digits);
63 for _ in digits.len()..p {
64 out.push('0');
65 }
66 out.push_str(".0");
67 } else {
68 out.push_str(digits.get(..p).unwrap_or_default());
69 out.push('.');
70 out.push_str(digits.get(p..).unwrap_or_default());
71 }
72 }
73 } else {
74 out.push_str(digits.get(..1).unwrap_or_default());
75 if digits.len() > 1 {
76 out.push('.');
77 out.push_str(digits.get(1..).unwrap_or_default());
78 }
79 out.push('e');
80 out.push(if exp < 0 { '-' } else { '+' });
81 let _ = write!(out, "{:02}", exp.unsigned_abs());
82 }
83 out
84}
85
86#[cfg(test)]
87mod tests {
88 use super::py_float_repr;
89
90 #[test]
91 fn floats_repr_as_python() {
92 for (x, s) in [
95 (4100.0, "4100.0"),
96 (1e16, "1e+16"),
97 (0.0001, "0.0001"),
98 (0.00001, "1e-05"),
99 (-2.5, "-2.5"),
100 (0.0, "0.0"),
101 (-0.0, "-0.0"),
102 (1.5e300, "1.5e+300"),
103 (f64::NAN, "nan"),
104 (f64::INFINITY, "inf"),
105 (f64::NEG_INFINITY, "-inf"),
106 (5e-324, "5e-324"),
107 ] {
108 assert_eq!(py_float_repr(x), s, "{x:e}");
109 }
110 }
111
112 #[test]
113 fn ties_go_to_the_even_digits_and_powers_of_two_to_the_nearest() {
114 for (exact, want) in [
119 ("1234567890123456.0", "1234567890123456.0"),
120 ("1551563132437320.25", "1551563132437320.2"),
121 ("-1551563132437320.25", "-1551563132437320.2"),
122 ("79686618578806.625", "79686618578806.62"),
123 ("1125899906842624.25", "1125899906842624.2"),
124 ("22620844907483.3125", "22620844907483.312"),
125 ("2.98023223876953125e-8", "2.9802322387695312e-08"),
126 ("5.9604644775390625e-7", "5.960464477539062e-07"),
127 ("9007199254740992.0", "9007199254740992.0"),
128 ] {
129 let x: f64 = exact.parse().unwrap();
130 assert_eq!(py_float_repr(x), want, "{exact}");
131 }
132 }
133}