Skip to main content

nodejs/
numfmt.rs

1//! `Number.prototype.toLocaleString` / `BigInt.prototype.toLocaleString` with
2//! their `options` argument, in the `en-US` shape.
3//!
4//! This is the ECMA-402 `Intl.NumberFormat` pipeline restricted to what needs no
5//! locale data beyond en-US: the digit options (`minimumIntegerDigits`,
6//! `minimum`/`maximumFractionDigits`, `minimum`/`maximumSignificantDigits`),
7//! `useGrouping`, and the `decimal`/`percent`/`currency` styles. The `locales`
8//! argument is still ignored (there is no ICU here, so every locale formats as
9//! en-US — see BUGS.md). `signDisplay` and `currencyDisplay: "code"` are
10//! honored; `notation`, the `name`/`narrowSymbol` currency displays and the
11//! `unit` style's unit label are not modelled.
12//!
13//! Rounding is ICU's: the number's SHORTEST round-trip decimal form is rounded
14//! half away from zero (`halfExpand`), so `(1.005).toLocaleString('en-US',
15//! {maximumFractionDigits: 2})` is `1.01` even though the binary value is just
16//! below 1.005 — which is where this differs from `toFixed`.
17
18use crate::host::{self, with_host};
19use fusevm::Value;
20
21/// The currencies whose en-US rendering is not "the ISO code, a no-break space,
22/// two fraction digits": `(code, symbol, fraction digits, NBSP after symbol)`.
23///
24/// GENERATED from node v26.10.0 (`Intl.supportedValuesOf('currency')`, each
25/// formatted with `formatToParts`); any code absent here — including a
26/// well-formed code ICU does not know, like `XYZ` — renders as `XYZ 1.00`.
27const CURRENCIES: &[(&str, &str, usize, bool)] = &[
28    ("AFN", "AFN", 0, true),
29    ("ALL", "ALL", 0, true),
30    ("AUD", "A$", 2, false),
31    ("BHD", "BHD", 3, true),
32    ("BIF", "BIF", 0, true),
33    ("BRL", "R$", 2, false),
34    ("CAD", "CA$", 2, false),
35    ("CLP", "CLP", 0, true),
36    ("CNY", "CN¥", 2, false),
37    ("COP", "COP", 0, true),
38    ("DJF", "DJF", 0, true),
39    ("EUR", "€", 2, false),
40    ("GBP", "£", 2, false),
41    ("GNF", "GNF", 0, true),
42    ("HKD", "HK$", 2, false),
43    ("HUF", "HUF", 0, true),
44    ("IDR", "IDR", 0, true),
45    ("ILS", "₪", 2, false),
46    ("INR", "₹", 2, false),
47    ("IQD", "IQD", 0, true),
48    ("IRR", "IRR", 0, true),
49    ("ISK", "ISK", 0, true),
50    ("JOD", "JOD", 3, true),
51    ("JPY", "¥", 0, false),
52    ("KMF", "KMF", 0, true),
53    ("KPW", "KPW", 0, true),
54    ("KRW", "₩", 0, false),
55    ("KWD", "KWD", 3, true),
56    ("LAK", "LAK", 0, true),
57    ("LBP", "LBP", 0, true),
58    ("LYD", "LYD", 3, true),
59    ("MGA", "MGA", 0, true),
60    ("MMK", "MMK", 0, true),
61    ("MXN", "MX$", 2, false),
62    ("NZD", "NZ$", 2, false),
63    ("OMR", "OMR", 3, true),
64    ("PHP", "₱", 2, false),
65    ("PKR", "PKR", 0, true),
66    ("PYG", "PYG", 0, true),
67    ("RWF", "RWF", 0, true),
68    ("SLL", "SLL", 0, true),
69    ("SOS", "SOS", 0, true),
70    ("SYP", "SYP", 0, true),
71    ("TND", "TND", 3, true),
72    ("TWD", "NT$", 2, false),
73    ("UGX", "UGX", 0, true),
74    ("USD", "$", 2, false),
75    ("VND", "₫", 0, false),
76    ("VUV", "VUV", 0, true),
77    ("XAF", "FCFA", 0, true),
78    ("XCD", "EC$", 2, false),
79    ("XCG", "Cg.", 2, true),
80    ("XOF", "F\u{202f}CFA", 0, true),
81    ("XPF", "CFPF", 0, true),
82    ("YER", "YER", 0, true),
83];
84
85/// The value being formatted. A BigInt is formatted from its exact digits.
86pub enum Num<'a> {
87    Float(f64),
88    /// The magnitude's decimal digits and whether it is negative.
89    BigInt(&'a str, bool),
90}
91
92enum Style {
93    Decimal,
94    Percent,
95    /// The prefix as rendered (`$`, `CHF\u{a0}`).
96    Currency(String),
97}
98
99#[derive(PartialEq)]
100enum SignDisplay {
101    Auto,
102    Always,
103    ExceptZero,
104    Negative,
105    Never,
106}
107
108enum Rounding {
109    Fraction { min: usize, max: usize },
110    Significant { min: usize, max: usize },
111}
112
113#[derive(PartialEq)]
114enum Grouping {
115    Always,
116    Min2,
117    Off,
118}
119
120struct Format {
121    style: Style,
122    sign: SignDisplay,
123    min_int: usize,
124    rounding: Rounding,
125    grouping: Grouping,
126}
127
128/// A non-negative decimal `0.d1d2…dn × 10^point`: `digits` has no leading
129/// zero (empty for zero), and `point` is how many of them precede the decimal
130/// point (negative or past the end for very small / very large values).
131struct Decimal {
132    digits: Vec<u8>,
133    point: i64,
134}
135
136impl Decimal {
137    /// The shortest round-trip decimal of a finite, non-negative `x`.
138    fn from_f64(x: f64) -> Decimal {
139        if x == 0.0 {
140            return Decimal {
141                digits: Vec::new(),
142                point: 0,
143            };
144        }
145        let (s, exp) = crate::host::shortest_digits(x);
146        let digits: Vec<u8> = s.bytes().map(|b| b - b'0').collect();
147        let mut d = Decimal {
148            digits,
149            point: i64::from(exp) + 1,
150        };
151        d.trim();
152        d
153    }
154
155    fn from_digits(s: &str) -> Decimal {
156        let digits: Vec<u8> = s.bytes().map(|b| b - b'0').collect();
157        let mut d = Decimal {
158            point: digits.len() as i64,
159            digits,
160        };
161        d.trim();
162        d
163    }
164
165    /// Drop leading and trailing zero digits, keeping the value.
166    fn trim(&mut self) {
167        let lead = self.digits.iter().take_while(|&&b| b == 0).count();
168        self.digits.drain(..lead);
169        self.point -= lead as i64;
170        while self.digits.last() == Some(&0) {
171            self.digits.pop();
172        }
173        if self.digits.is_empty() {
174            self.point = 0;
175        }
176    }
177
178    /// Keep the first `keep` digits, rounding half away from zero on the rest.
179    fn round_to(&mut self, keep: i64) {
180        let n = self.digits.len() as i64;
181        if keep >= n {
182            return;
183        }
184        if keep < 0 {
185            self.digits.clear();
186            self.point = 0;
187            return;
188        }
189        let up = self.digits[keep as usize] >= 5;
190        self.digits.truncate(keep as usize);
191        if up {
192            let mut i = self.digits.len();
193            loop {
194                if i == 0 {
195                    self.digits.insert(0, 1);
196                    self.point += 1;
197                    break;
198                }
199                i -= 1;
200                if self.digits[i] == 9 {
201                    self.digits[i] = 0;
202                } else {
203                    self.digits[i] += 1;
204                    break;
205                }
206            }
207        }
208        self.trim();
209    }
210
211    /// Multiply by 100 (the percent style), exactly.
212    fn times_100(&mut self) {
213        if !self.digits.is_empty() {
214            self.point += 2;
215        }
216    }
217
218    /// `(integer digits, fraction digits)` with no padding.
219    fn split(&self) -> (String, String) {
220        let digit = |i: i64| -> char {
221            if i >= 0 && (i as usize) < self.digits.len() {
222                (b'0' + self.digits[i as usize]) as char
223            } else {
224                '0'
225            }
226        };
227        let int: String = if self.point > 0 {
228            (0..self.point).map(digit).collect()
229        } else {
230            String::new()
231        };
232        let frac_len = self.digits.len() as i64 - self.point;
233        let frac: String = (self.point..self.point + frac_len.max(0))
234            .map(digit)
235            .collect();
236        (int, frac)
237    }
238}
239
240/// V8's RangeError for an option value outside its allowed set.
241fn out_of_range(value: &str, name: &str) -> String {
242    host::range_error(&format!(
243        "Value {value} out of range for Number.prototype.toLocaleString options property {name}"
244    ))
245}
246
247/// `GetOption` for a string option restricted to `allowed`.
248fn enum_option(opts: &Value, name: &str, allowed: &[&str]) -> Result<Option<String>, String> {
249    match string_option(opts, name)? {
250        Some(s) if !allowed.contains(&s.as_str()) => Err(out_of_range(&s, name)),
251        other => Ok(other),
252    }
253}
254
255/// `GetNumberOption`: `undefined` → `None`; otherwise `ToNumber`, a RangeError
256/// outside `[lo, hi]` (or NaN), then `floor`.
257fn digit_option(opts: &Value, name: &str, lo: f64, hi: f64) -> Result<Option<usize>, String> {
258    let v = crate::builtins::get_property(opts, name)?;
259    if matches!(v, Value::Undef) {
260        return Ok(None);
261    }
262    let n = host::to_number_value(&v)?;
263    if n.is_nan() || n < lo || n > hi {
264        return Err(host::range_error(&format!("{name} value is out of range.")));
265    }
266    Ok(Some(n.floor() as usize))
267}
268
269/// `GetOption` for a string-valued option, `None` when absent.
270fn string_option(opts: &Value, name: &str) -> Result<Option<String>, String> {
271    let v = crate::builtins::get_property(opts, name)?;
272    if matches!(v, Value::Undef) {
273        return Ok(None);
274    }
275    Ok(Some(to_str(&v)?))
276}
277
278fn read_format(opts: &Value) -> Result<Format, String> {
279    if with_host(|h| h.is_null(opts)) {
280        return Err(host::type_error(
281            "Number.prototype.toLocaleString called on null or undefined",
282        ));
283    }
284    // A primitive `options` is `ToObject`ed in the spec, and a wrapper owns none
285    // of these keys, so it formats exactly as `undefined` does.
286    let is_object = matches!(opts, Value::Obj(_)) && !with_host(|h| host::is_primitive(h, opts));
287    if !is_object {
288        return Ok(Format {
289            style: Style::Decimal,
290            sign: SignDisplay::Auto,
291            min_int: 1,
292            rounding: Rounding::Fraction { min: 0, max: 3 },
293            grouping: Grouping::Always,
294        });
295    }
296    // Read in `InitializeNumberFormat` order, so the first invalid option is
297    // the one reported: style, currency, currencyDisplay, the digit options,
298    // useGrouping, signDisplay.
299    let style_name = enum_option(opts, "style", &["decimal", "percent", "currency", "unit"])?
300        .unwrap_or_else(|| "decimal".into());
301    // A malformed code is refused whatever the style (`IsWellFormedCurrencyCode`).
302    let currency = string_option(opts, "currency")?;
303    if let Some(code) = &currency {
304        if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_alphabetic()) {
305            return Err(host::range_error(&format!(
306                "Invalid currency code : {code}"
307            )));
308        }
309    }
310    let display = enum_option(
311        opts,
312        "currencyDisplay",
313        &["code", "symbol", "narrowSymbol", "name"],
314    )?;
315    let (style, currency_digits) = match style_name.as_str() {
316        "percent" => (Style::Percent, None),
317        "currency" => {
318            let Some(code) = currency else {
319                return Err(host::type_error(
320                    "Currency code is required with currency style.",
321                ));
322            };
323            let code = code.to_ascii_uppercase();
324            let known = CURRENCIES.iter().find(|(c, ..)| *c == code);
325            let digits = known.map(|(_, _, d, _)| *d).unwrap_or(2);
326            // `code` always spells the ISO code; `symbol` (and, not modelled,
327            // `narrowSymbol`/`name`) uses the en-US symbol table.
328            let prefix = match (display.as_deref(), known) {
329                (Some("code"), _) | (_, None) => format!("{code}\u{a0}"),
330                (_, Some((_, sym, _, spaced))) => {
331                    let gap = if *spaced { "\u{a0}" } else { "" };
332                    format!("{sym}{gap}")
333                }
334            };
335            (Style::Currency(prefix), Some(digits))
336        }
337        // `unit` needs per-unit display data; its number formats as decimal.
338        _ => (Style::Decimal, None),
339    };
340    let min_int = digit_option(opts, "minimumIntegerDigits", 1.0, 21.0)?.unwrap_or(1);
341    let min_frac = digit_option(opts, "minimumFractionDigits", 0.0, 100.0)?;
342    let max_frac = digit_option(opts, "maximumFractionDigits", 0.0, 100.0)?;
343    // `SetNumberFormatDigitOptions`: significant digits win when either is set.
344    let min_sig = digit_option(opts, "minimumSignificantDigits", 1.0, 21.0)?;
345    let max_sig = digit_option(opts, "maximumSignificantDigits", 1.0, 21.0)?;
346    let rounding = if min_sig.is_some() || max_sig.is_some() {
347        let min = min_sig.unwrap_or(1);
348        let max = max_sig.unwrap_or(21);
349        if min > max {
350            return Err(host::range_error(
351                "maximumSignificantDigits value is out of range.",
352            ));
353        }
354        Rounding::Significant { min, max }
355    } else {
356        let (min_default, max_default) = match (&style, currency_digits) {
357            (_, Some(d)) => (d, d),
358            (Style::Percent, _) => (0, 0),
359            _ => (0, 3),
360        };
361        let (min, max) = match (min_frac, max_frac) {
362            (None, None) => (min_default, max_default),
363            (Some(mn), None) => (mn, mn.max(max_default)),
364            (None, Some(mx)) => (min_default.min(mx), mx),
365            (Some(mn), Some(mx)) => {
366                if mn > mx {
367                    return Err(host::range_error(
368                        "maximumFractionDigits value is out of range.",
369                    ));
370                }
371                (mn, mx)
372            }
373        };
374        Rounding::Fraction { min, max }
375    };
376    // `GetBooleanOrStringNumberFormatOption`: `true` is "always", any other
377    // falsy value turns grouping off, and the strings "true"/"false" select
378    // the default ("auto", which groups in en-US).
379    let grouping_v = crate::builtins::get_property(opts, "useGrouping")?;
380    let grouping = match grouping_v {
381        Value::Undef | Value::Bool(true) => Grouping::Always,
382        ref v if !with_host(|h| h.truthy(v)) => Grouping::Off,
383        ref v => match to_str(v)?.as_str() {
384            "min2" => Grouping::Min2,
385            "always" | "auto" | "true" | "false" => Grouping::Always,
386            other => return Err(out_of_range(other, "useGrouping")),
387        },
388    };
389    let sign = match enum_option(
390        opts,
391        "signDisplay",
392        &["auto", "never", "always", "exceptZero", "negative"],
393    )?
394    .as_deref()
395    {
396        Some("never") => SignDisplay::Never,
397        Some("always") => SignDisplay::Always,
398        Some("exceptZero") => SignDisplay::ExceptZero,
399        Some("negative") => SignDisplay::Negative,
400        _ => SignDisplay::Auto,
401    };
402    Ok(Format {
403        style,
404        sign,
405        min_int,
406        rounding,
407        grouping,
408    })
409}
410
411fn group(int: &str, grouping: &Grouping) -> String {
412    if *grouping == Grouping::Off || (*grouping == Grouping::Min2 && int.len() < 5) {
413        return int.to_string();
414    }
415    let mut out = String::with_capacity(int.len() + int.len() / 3);
416    for (i, c) in int.chars().enumerate() {
417        if i > 0 && (int.len() - i) % 3 == 0 {
418            out.push(',');
419        }
420        out.push(c);
421    }
422    out
423}
424
425/// Format `x` the way `x.toLocaleString(locales, opts)` does under en-US.
426pub fn to_locale_string(x: Num, opts: &Value) -> Result<String, String> {
427    let fmt = read_format(opts)?;
428    let (neg, mut dec, special) = match x {
429        Num::Float(f) if f.is_nan() => (false, Decimal::from_digits(""), Some("NaN")),
430        Num::Float(f) if f.is_infinite() => (f < 0.0, Decimal::from_digits(""), Some("∞")),
431        Num::Float(f) => (f.is_sign_negative(), Decimal::from_f64(f.abs()), None),
432        Num::BigInt(digits, neg) => (neg, Decimal::from_digits(digits), None),
433    };
434    let body = if let Some(text) = special {
435        text.to_string()
436    } else {
437        if matches!(fmt.style, Style::Percent) {
438            dec.times_100();
439        }
440        let (min_frac_shown, min_sig) = match fmt.rounding {
441            Rounding::Fraction { min, max } => {
442                dec.round_to(dec.point + max as i64);
443                (min, None)
444            }
445            Rounding::Significant { min, max } => {
446                dec.round_to(max as i64);
447                (0, Some(min))
448            }
449        };
450        let (mut int, mut frac) = dec.split();
451        if int.len() < fmt.min_int {
452            int = format!("{}{int}", "0".repeat(fmt.min_int - int.len()));
453        }
454        let mut min_frac = min_frac_shown;
455        if let Some(min_sig) = min_sig {
456            // Pad to `minimumSignificantDigits`, counted from the first
457            // non-zero digit; a zero counts its units digit as the one it has.
458            let sig_int = int.trim_start_matches('0').len();
459            let lead_frac_zeros = if sig_int == 0 {
460                frac.bytes().take_while(|&b| b == b'0').count()
461            } else {
462                0
463            };
464            let have = (sig_int + frac.len() - lead_frac_zeros).max(1);
465            min_frac = frac.len() + min_sig.saturating_sub(have);
466        }
467        while frac.len() < min_frac {
468            frac.push('0');
469        }
470        let grouped = group(&int, &fmt.grouping);
471        if frac.is_empty() {
472            grouped
473        } else {
474            format!("{grouped}.{frac}")
475        }
476    };
477    // The sign is decided on the ROUNDED value: `-0.0001` rounds to zero, and
478    // only `auto`/`always` still show its minus.
479    let zero = special.is_none() && dec.digits.is_empty();
480    let nan = special == Some("NaN");
481    let sign = match fmt.sign {
482        SignDisplay::Never => "",
483        SignDisplay::ExceptZero if zero || nan => "",
484        SignDisplay::Negative if zero => "",
485        _ if neg => "-",
486        SignDisplay::Always | SignDisplay::ExceptZero => "+",
487        _ => "",
488    };
489    Ok(match fmt.style {
490        Style::Decimal => format!("{sign}{body}"),
491        Style::Percent => format!("{sign}{body}%"),
492        Style::Currency(prefix) => format!("{sign}{prefix}{body}"),
493    })
494}
495
496/// `ToString` of an option value, running a user `toString`.
497fn to_str(v: &Value) -> Result<String, String> {
498    let s = host::to_string_value(v)?;
499    Ok(with_host(|h| h.str_of(&s)))
500}