Skip to main content

php_std/
number.rs

1//! How PHP prints floats.
2//!
3//! PHP formats floats with `zend_gcvt`: `ndigit` significant digits (mode 2),
4//! or the shortest round-trip digits when the precision setting is `-1`
5//! (mode 0, exponent threshold 17), switching to exponent notation when the
6//! decimal point is more than `ndigit` places right or more than 3 places
7//! left of the digits. The mantissa always has a fraction (`1.0E+25`).
8//!
9//! - `(string) $float`, `echo`, string interpolation, string comparison use
10//!   the `precision` setting ([`PRECISION`], -1 as Appwrite's `php.ini` sets
11//!   it): [`to_string`].
12//! - `json_encode`, `var_export` use `serialize_precision` (-1) and a
13//!   lowercase `e`: [`serialize`].
14
15use std::fmt::Write as _;
16
17/// The `precision` ini Appwrite runs PHP with (`docker/php.ini`): `-1`, the
18/// shortest round-trip digits, so floats keep every digit when they become
19/// strings (PDO binds and fetches them as strings at this setting). PHP's own
20/// default is 14; [`gcvt`] prints at any other setting.
21pub const PRECISION: i32 = -1;
22
23/// `(string) $float` at the `precision` setting ([`PRECISION`]).
24pub fn to_string(f: f64) -> String {
25    gcvt(f, PRECISION, 'E')
26}
27
28/// `json_encode($float)` / `var_export` with `serialize_precision = -1`.
29pub fn serialize(f: f64) -> String {
30    gcvt(f, -1, 'e')
31}
32
33/// [`serialize`], appended to `out` (no allocation of its own).
34pub(crate) fn serialize_into(out: &mut Vec<u8>, f: f64) {
35    gcvt_into(out, f, -1, b'e');
36}
37
38/// `zend_gcvt(value, precision, '.', exp_char)`, with PHP's special values.
39/// `precision` is the ini value: `-1` selects the shortest round-trip digits.
40pub fn gcvt(value: f64, precision: i32, exp_char: char) -> String {
41    let mut out = Vec::with_capacity(24);
42    gcvt_into(&mut out, value, precision, exp_char as u8);
43    // ASCII digits, signs, '.', and the ASCII exponent character.
44    String::from_utf8(out).unwrap_or_default()
45}
46
47/// [`gcvt`], appended to `out`; `exp_char` is an ASCII letter.
48pub(crate) fn gcvt_into(out: &mut Vec<u8>, value: f64, precision: i32, exp_char: u8) {
49    if value.is_nan() {
50        out.extend_from_slice(b"NAN");
51        return;
52    }
53    if value.is_infinite() {
54        out.extend_from_slice(if value > 0.0 { b"INF" } else { b"-INF" });
55        return;
56    }
57    let mut digits = Digits::new();
58    let (ndigit, decpt) = if precision < 0 {
59        (17, digits.shortest(value.abs()))
60    } else {
61        let n = precision.max(1) as usize;
62        (n as i32, digits.rounded(value.abs(), n))
63    };
64    let digits = digits.as_bytes();
65    if value.is_sign_negative() {
66        out.push(b'-');
67    }
68    if decpt < -3 || decpt > ndigit {
69        let exp = decpt - 1;
70        out.push(digits[0]);
71        out.push(b'.');
72        out.extend_from_slice(if digits.len() > 1 { &digits[1..] } else { b"0" });
73        out.push(exp_char);
74        out.push(if exp < 0 { b'-' } else { b'+' });
75        crate::json::push_int(out, i64::from(exp.unsigned_abs()));
76    } else if decpt < 0 {
77        out.extend_from_slice(b"0.");
78        for _ in decpt..0 {
79            out.push(b'0');
80        }
81        out.extend_from_slice(digits);
82    } else {
83        let decpt = decpt as usize;
84        if decpt <= digits.len() {
85            out.extend_from_slice(&digits[..decpt]);
86        } else {
87            out.extend_from_slice(digits);
88            out.resize(out.len() + decpt - digits.len(), b'0');
89        }
90        if decpt < digits.len() {
91            if decpt == 0 {
92                out.push(b'0');
93            }
94            out.push(b'.');
95            out.extend_from_slice(&digits[decpt..]);
96        }
97    }
98}
99
100/// Whether `zend_dtoa` keeps the trailing zeros of the `n` digits it rounds
101/// `v` (not negative) to: `v` is an integer below 1e15 whose digits after
102/// the first `n` are exactly half a unit, rounded down to even. Its
103/// floating-point fast path cannot decide that tie, and the "small integer"
104/// path it falls back to returns the `n` digits without removing zeros
105/// (`printf("%G", 4975205)` is `4.97520E+6`).
106fn tie_rounded_down(v: f64, n: usize) -> bool {
107    if v.fract() != 0.0 || v >= 1e15 {
108        return false;
109    }
110    let int = v as u64;
111    let digits = int.checked_ilog10().map_or(1, |l| l as usize + 1);
112    if digits <= n {
113        return false;
114    }
115    let unit = 10u64.pow((digits - n) as u32);
116    int % unit * 2 == unit && (int / unit).is_multiple_of(2)
117}
118
119/// Significant decimal digits of a float, on the stack: the shortest
120/// round-trip digits (Ryū), or the requested number correctly rounded
121/// (Rust's `{:e}`), without trailing zeros as `zend_dtoa` returns them.
122struct Digits {
123    buf: [u8; 32],
124    len: usize,
125    /// The digits when `{:e}` does not fit in `buf` (a precision above 25).
126    heap: Vec<u8>,
127}
128
129impl std::fmt::Write for Digits {
130    /// Appends `s` to the buffer, or fails when it does not fit.
131    fn write_str(&mut self, s: &str) -> std::fmt::Result {
132        let end = self.len + s.len();
133        let dest = self.buf.get_mut(self.len..end).ok_or(std::fmt::Error)?;
134        dest.copy_from_slice(s.as_bytes());
135        self.len = end;
136        Ok(())
137    }
138}
139
140impl Digits {
141    fn new() -> Self {
142        Digits { buf: [0; 32], len: 0, heap: Vec::new() }
143    }
144
145    /// Shortest round-trip digits of `v` (not negative); returns the decimal
146    /// point position (`v = 0.DIGITS × 10^decpt`). Zero is `"0"` at 1.
147    fn shortest(&mut self, v: f64) -> i32 {
148        if v == 0.0 {
149            return self.zero();
150        }
151        // Ryū's shortest form: "123.456", "0.001", "1e25" or "1.5e-7".
152        let mut buffer = ryu::Buffer::new();
153        let text = buffer.format_finite(v).as_bytes();
154        let (mantissa, exp) = match text.iter().position(|&b| b == b'e') {
155            Some(e) => (&text[..e], std::str::from_utf8(&text[e + 1..]).ok().and_then(|x| x.parse().ok())),
156            None => (text, Some(0)),
157        };
158        let point = mantissa.iter().position(|&b| b == b'.').unwrap_or(mantissa.len());
159        let mut decpt = point as i32 + exp.unwrap_or(0);
160        let mut len = 0;
161        for &b in mantissa.iter().filter(|b| b.is_ascii_digit()) {
162            if len == 0 && b == b'0' {
163                // A leading zero: the point is one place further left.
164                decpt -= 1;
165            } else {
166                self.buf[len] = b;
167                len += 1;
168            }
169        }
170        while len > 1 && self.buf[len - 1] == b'0' {
171            len -= 1;
172        }
173        self.len = len;
174        decpt
175    }
176
177    /// `n` correctly rounded significant digits of `v` (not negative).
178    fn rounded(&mut self, v: f64, n: usize) -> i32 {
179        if v == 0.0 {
180            return self.zero();
181        }
182        if write!(self, "{v:.*e}", n - 1).is_err() {
183            self.heap = format!("{v:.*e}", n - 1).into_bytes();
184        }
185        self.split(!tie_rounded_down(v, n))
186    }
187
188    fn zero(&mut self) -> i32 {
189        self.buf[0] = b'0';
190        self.len = 1;
191        1
192    }
193
194    /// `"1.2345e-3"` in place -> digits `"12345"`, returns `-2`. Trailing
195    /// zeros are removed when `strip`.
196    fn split(&mut self, strip: bool) -> i32 {
197        let text: &mut [u8] = if self.heap.is_empty() { &mut self.buf[..self.len] } else { &mut self.heap };
198        let e = text.iter().position(|&b| b == b'e').unwrap_or(text.len());
199        let exp = std::str::from_utf8(&text[(e + 1).min(text.len())..]).ok().and_then(|x| x.parse::<i32>().ok());
200        // The mantissa's digits, moved over the point.
201        let mut len = 0;
202        for i in 0..e {
203            if text[i].is_ascii_digit() {
204                text[len] = text[i];
205                len += 1;
206            }
207        }
208        while strip && len > 1 && text[len - 1] == b'0' {
209            len -= 1;
210        }
211        if self.heap.is_empty() {
212            self.len = len;
213        } else {
214            self.heap.truncate(len);
215        }
216        exp.unwrap_or(0) + 1
217    }
218
219    fn as_bytes(&self) -> &[u8] {
220        if self.heap.is_empty() { &self.buf[..self.len] } else { &self.heap }
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn strings_like_php() {
230        // `precision = -1`: the shortest round-trip digits.
231        assert_eq!(to_string(0.1), "0.1");
232        assert_eq!(to_string(0.1 + 0.2), "0.30000000000000004");
233        assert_eq!(to_string(1e25), "1.0E+25");
234        assert_eq!(to_string(1.0), "1");
235        assert_eq!(to_string(-0.0), "-0");
236        assert_eq!(to_string(0.00001), "1.0E-5");
237        assert_eq!(to_string(0.0001), "0.0001");
238        assert_eq!(to_string(123456789012345678.0), "1.2345678901234568E+17");
239        assert_eq!(to_string(1e15), "1000000000000000");
240        assert_eq!(to_string(1e14), "100000000000000");
241        assert_eq!(to_string(100000000000005.0), "100000000000005");
242        assert_eq!(to_string(f64::INFINITY), "INF");
243        // `precision = 14`, PHP's own default.
244        assert_eq!(gcvt(0.1 + 0.2, 14, 'E'), "0.3");
245        assert_eq!(gcvt(123456789012345678.0, 14, 'E'), "1.2345678901235E+17");
246        assert_eq!(gcvt(1e15, 14, 'E'), "1.0E+15");
247        assert_eq!(gcvt(1e14, 14, 'E'), "1.0E+14");
248        assert_eq!(gcvt(1e13, 14, 'E'), "10000000000000");
249        // A tie rounded down keeps its zeros, as `zend_dtoa`'s small-integer path does.
250        assert_eq!(gcvt(100000000000005.0, 14, 'E'), "1.0000000000000E+14");
251        assert_eq!(gcvt(4975205.0, 6, 'E'), "4.97520E+6");
252        assert_eq!(gcvt(4975005.0, 6, 'E'), "4.97500E+6");
253        assert_eq!(gcvt(125.0, 2, 'E'), "1.2E+2");
254        assert_eq!(gcvt(25.0, 1, 'E'), "2.0E+1");
255        assert_eq!(gcvt(4975215.0, 6, 'E'), "4.97522E+6");
256    }
257
258    #[test]
259    fn serialized_like_php() {
260        assert_eq!(serialize(0.1 + 0.2), "0.30000000000000004");
261        assert_eq!(serialize(1.0), "1");
262        assert_eq!(serialize(1e25), "1.0e+25");
263        assert_eq!(serialize(-0.0), "-0");
264        assert_eq!(serialize(1e15), "1000000000000000");
265        assert_eq!(serialize(0.00001), "1.0e-5");
266        // Exactly between two shortest forms (…323.25): PHP, as Ryū, prints the even one.
267        assert_eq!(serialize(1690060720831323.3), "1690060720831323.2");
268        assert_eq!(serialize(-163559682789802.63), "-163559682789802.62");
269    }
270}