Skip to main content

sheetkit_core/
numfmt.rs

1//! Number format renderer: converts a (value, format_code) pair into display text.
2//!
3//! Supports Excel built-in format IDs 0-49, custom numeric patterns
4//! (`0`, `#`, `,`, `.`, `%`, `E+`), date/time patterns (`y`, `m`, `d`,
5//! `h`, `s`, `AM/PM`), multi-section formats (up to 4 sections separated
6//! by `;`), color codes (`[Red]`, `[Blue]`, etc.), conditional sections
7//! (`[>100]`), text format (`@`), and fraction formats (`# ?/?`).
8
9use crate::cell::serial_to_date;
10
11/// Map a built-in number format ID (0-49) to its format code string.
12pub fn builtin_format_code(id: u32) -> Option<&'static str> {
13    match id {
14        0 => Some("General"),
15        1 => Some("0"),
16        2 => Some("0.00"),
17        3 => Some("#,##0"),
18        4 => Some("#,##0.00"),
19        5 => Some("#,##0_);(#,##0)"),
20        6 => Some("#,##0_);[Red](#,##0)"),
21        7 => Some("#,##0.00_);(#,##0.00)"),
22        8 => Some("#,##0.00_);[Red](#,##0.00)"),
23        9 => Some("0%"),
24        10 => Some("0.00%"),
25        11 => Some("0.00E+00"),
26        12 => Some("# ?/?"),
27        13 => Some("# ??/??"),
28        14 => Some("m/d/yyyy"),
29        15 => Some("d-mmm-yy"),
30        16 => Some("d-mmm"),
31        17 => Some("mmm-yy"),
32        18 => Some("h:mm AM/PM"),
33        19 => Some("h:mm:ss AM/PM"),
34        20 => Some("h:mm"),
35        21 => Some("h:mm:ss"),
36        22 => Some("m/d/yyyy h:mm"),
37        37 => Some("#,##0_);(#,##0)"),
38        38 => Some("#,##0_);[Red](#,##0)"),
39        39 => Some("#,##0.00_);(#,##0.00)"),
40        40 => Some("#,##0.00_);[Red](#,##0.00)"),
41        41 => Some(r#"_(* #,##0_);_(* \(#,##0\);_(* "-"_);_(@_)"#),
42        42 => Some(r#"_("$"* #,##0_);_("$"* \(#,##0\);_("$"* "-"_);_(@_)"#),
43        43 => Some(r#"_(* #,##0.00_);_(* \(#,##0.00\);_(* "-"??_);_(@_)"#),
44        44 => Some(r#"_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)"#),
45        45 => Some("mm:ss"),
46        46 => Some("[h]:mm:ss"),
47        47 => Some("mm:ss.0"),
48        48 => Some("##0.0E+0"),
49        49 => Some("@"),
50        _ => None,
51    }
52}
53
54/// Format a numeric value using the given format code string.
55///
56/// Returns the formatted display text. For format codes that contain date/time
57/// tokens, the value is interpreted as an Excel serial number.
58pub fn format_number(value: f64, format_code: &str) -> String {
59    if format_code.is_empty() || format_code.eq_ignore_ascii_case("General") {
60        return format_general(value);
61    }
62
63    let sections = parse_sections(format_code);
64
65    let has_any_condition = sections.iter().any(|s| extract_condition(s).is_some());
66    let section = pick_section(&sections, value);
67
68    let (cleaned, _color) = strip_color_and_condition(section);
69
70    // Standard negative sections format the magnitude. Conditional sections
71    // still receive the signed value; their selected pattern may or may not
72    // supply the sign presentation.
73    let use_abs = !has_any_condition && sections.len() >= 2 && value < 0.0;
74    let effective_value = if use_abs { value.abs() } else { value };
75
76    if cleaned == "@" {
77        return format_general(effective_value);
78    }
79
80    if is_date_time_format(&cleaned) {
81        return format_date_time(effective_value, &cleaned);
82    }
83
84    if cleaned.contains('?') && cleaned.contains('/') {
85        return format_fraction(effective_value, &cleaned);
86    }
87
88    if format_has_unquoted_char(&cleaned, 'E') || format_has_unquoted_char(&cleaned, 'e') {
89        return format_scientific(effective_value, &cleaned);
90    }
91
92    format_numeric(effective_value, &cleaned)
93}
94
95/// Format a numeric value using a built-in format ID.
96/// Returns `None` if the ID is not a recognized built-in format.
97pub fn format_with_builtin(value: f64, id: u32) -> Option<String> {
98    let code = builtin_format_code(id)?;
99    Some(format_number(value, code))
100}
101
102fn format_general(value: f64) -> String {
103    if value == 0.0 {
104        return "0".to_string();
105    }
106    if value.fract() == 0.0 && value.is_finite() && value.abs() < 1e15 {
107        return format!("{}", value as i64);
108    }
109    // Excel displays up to ~11 significant digits in General format.
110    let abs = value.abs();
111    if (1e-4..1e15).contains(&abs) {
112        let s = format!("{:.10}", value);
113        trim_trailing_zeros(&s)
114    } else if abs < 1e-4 && abs > 0.0 {
115        format!("{:.6E}", value)
116    } else {
117        format!("{}", value)
118    }
119}
120
121fn trim_trailing_zeros(s: &str) -> String {
122    if let Some(dot) = s.find('.') {
123        let trimmed = s.trim_end_matches('0');
124        if trimmed.len() == dot + 1 {
125            trimmed[..dot].to_string()
126        } else {
127            trimmed.to_string()
128        }
129    } else {
130        s.to_string()
131    }
132}
133
134fn parse_sections(format_code: &str) -> Vec<&str> {
135    let mut sections = Vec::new();
136    let mut start = 0;
137    let mut in_quotes = false;
138    let mut prev_backslash = false;
139
140    for (i, ch) in format_code.char_indices() {
141        if prev_backslash {
142            prev_backslash = false;
143            continue;
144        }
145        if ch == '\\' {
146            prev_backslash = true;
147            continue;
148        }
149        if ch == '"' {
150            in_quotes = !in_quotes;
151            continue;
152        }
153        if !in_quotes && ch == ';' {
154            sections.push(&format_code[start..i]);
155            start = i + 1;
156        }
157    }
158    sections.push(&format_code[start..]);
159    sections
160}
161
162/// Comparison operator for conditional format sections.
163#[derive(Debug, Clone, Copy, PartialEq)]
164enum ConditionOp {
165    Gt,
166    Ge,
167    Lt,
168    Le,
169    Eq,
170    Ne,
171}
172
173/// A parsed conditional predicate from a format section (e.g., `[>100]`).
174#[derive(Debug, Clone, PartialEq)]
175struct Condition {
176    op: ConditionOp,
177    threshold: f64,
178}
179
180impl Condition {
181    fn matches(&self, value: f64) -> bool {
182        match self.op {
183            ConditionOp::Gt => value > self.threshold,
184            ConditionOp::Ge => value >= self.threshold,
185            ConditionOp::Lt => value < self.threshold,
186            ConditionOp::Le => value <= self.threshold,
187            ConditionOp::Eq => (value - self.threshold).abs() < 1e-12,
188            ConditionOp::Ne => (value - self.threshold).abs() >= 1e-12,
189        }
190    }
191}
192
193/// Parse a bracket's inner content as a conditional predicate.
194/// Returns `Some(Condition)` for strings like `>100`, `<=0`, `<>5`, `=0`.
195fn parse_condition(content: &str) -> Option<Condition> {
196    let s = content.trim();
197    if s.is_empty() {
198        return None;
199    }
200
201    // Try two-character operators first, then single-character
202    let (op, rest) = if let Some(r) = s.strip_prefix(">=") {
203        (ConditionOp::Ge, r)
204    } else if let Some(r) = s.strip_prefix("<=") {
205        (ConditionOp::Le, r)
206    } else if let Some(r) = s.strip_prefix("<>").or_else(|| s.strip_prefix("!=")) {
207        (ConditionOp::Ne, r)
208    } else if let Some(r) = s.strip_prefix('>') {
209        (ConditionOp::Gt, r)
210    } else if let Some(r) = s.strip_prefix('<') {
211        (ConditionOp::Lt, r)
212    } else {
213        (ConditionOp::Eq, s.strip_prefix('=')?)
214    };
215
216    let threshold: f64 = rest.trim().parse().ok()?;
217    Some(Condition { op, threshold })
218}
219
220/// Extract the condition (if any) from a format section's bracket content.
221fn extract_condition(section: &str) -> Option<Condition> {
222    let mut chars = section.chars().peekable();
223    while let Some(&ch) = chars.peek() {
224        if ch == '[' {
225            chars.next();
226            let mut bracket_content = String::new();
227            while let Some(&c) = chars.peek() {
228                if c == ']' {
229                    chars.next();
230                    break;
231                }
232                bracket_content.push(c);
233                chars.next();
234            }
235            let lower = bracket_content.to_ascii_lowercase();
236            let is_known_non_condition = is_color_code(&lower)
237                || lower.starts_with("dbnum")
238                || lower.starts_with('$')
239                || lower.starts_with("natnum")
240                || (lower.starts_with('h') && lower.contains(':'))
241                || lower.starts_with("mm")
242                || lower.starts_with("ss");
243            if !is_known_non_condition {
244                if let Some(cond) = parse_condition(&bracket_content) {
245                    return Some(cond);
246                }
247            }
248        } else {
249            chars.next();
250        }
251    }
252    None
253}
254
255/// Pick the format section to apply for a given value.
256///
257/// When sections contain explicit conditional predicates (e.g., `[>100]`),
258/// those conditions are evaluated against the value. Otherwise, the standard
259/// Excel sign-based selection (positive / negative / zero / text) is used.
260fn pick_section<'a>(sections: &[&'a str], value: f64) -> &'a str {
261    // Gather conditions from each section
262    let conditions: Vec<Option<Condition>> =
263        sections.iter().map(|s| extract_condition(s)).collect();
264
265    let has_any_condition = conditions.iter().any(|c| c.is_some());
266
267    if has_any_condition {
268        // Find the first section whose condition matches
269        for (i, cond) in conditions.iter().enumerate() {
270            if let Some(c) = cond {
271                if c.matches(value) {
272                    return sections[i];
273                }
274            }
275        }
276        // No conditional section matched: use the first section without a condition
277        // as the fallback (this is how Excel handles it)
278        for (i, cond) in conditions.iter().enumerate() {
279            if cond.is_none() {
280                return sections[i];
281            }
282        }
283        // All sections have conditions and none matched: use the last section
284        return sections.last().unwrap_or(&"General");
285    }
286
287    // Standard sign-based selection (no conditional predicates)
288    match sections.len() {
289        1 => sections[0],
290        2 => {
291            if value >= 0.0 {
292                sections[0]
293            } else {
294                sections[1]
295            }
296        }
297        3 | 4.. => {
298            if value > 0.0 {
299                sections[0]
300            } else if value < 0.0 {
301                sections[1]
302            } else {
303                sections[2]
304            }
305        }
306        _ => "General",
307    }
308}
309
310/// Strip color codes and conditional predicates from a format section,
311/// returning the cleaned format string and the color name (if any).
312fn strip_color_and_condition(section: &str) -> (String, Option<String>) {
313    let mut result = String::with_capacity(section.len());
314    let mut color = None;
315    let mut chars = section.chars().peekable();
316
317    while let Some(&ch) = chars.peek() {
318        if ch == '[' {
319            let mut bracket_content = String::new();
320            chars.next(); // consume '['
321            while let Some(&c) = chars.peek() {
322                if c == ']' {
323                    chars.next(); // consume ']'
324                    break;
325                }
326                bracket_content.push(c);
327                chars.next();
328            }
329            let lower = bracket_content.to_ascii_lowercase();
330            if is_color_code(&lower) {
331                color = Some(bracket_content);
332            } else if lower.starts_with('h') && lower.contains(':') {
333                // Elapsed time bracket like [h] or [hh]
334                result.push('[');
335                result.push_str(&bracket_content);
336                result.push(']');
337            } else if lower.starts_with("mm") || lower.starts_with("ss") {
338                result.push('[');
339                result.push_str(&bracket_content);
340                result.push(']');
341            } else if parse_condition(&bracket_content).is_some() {
342                // Conditional predicate -- strip from format string
343                // (condition is evaluated during section selection)
344            } else if lower.starts_with("dbnum")
345                || lower.starts_with("$")
346                || lower.starts_with("natnum")
347            {
348                // Locale or special -- skip
349            } else {
350                // Unknown bracket, preserve
351                result.push('[');
352                result.push_str(&bracket_content);
353                result.push(']');
354            }
355        } else {
356            result.push(ch);
357            chars.next();
358        }
359    }
360
361    (result, color)
362}
363
364fn is_color_code(lower: &str) -> bool {
365    matches!(
366        lower,
367        "red"
368            | "blue"
369            | "green"
370            | "yellow"
371            | "cyan"
372            | "magenta"
373            | "white"
374            | "black"
375            | "color1"
376            | "color2"
377            | "color3"
378            | "color4"
379            | "color5"
380            | "color6"
381            | "color7"
382            | "color8"
383            | "color9"
384            | "color10"
385    )
386}
387
388fn is_date_time_format(format: &str) -> bool {
389    let mut in_quotes = false;
390    let mut prev_backslash = false;
391    for ch in format.chars() {
392        if prev_backslash {
393            prev_backslash = false;
394            continue;
395        }
396        if ch == '\\' {
397            prev_backslash = true;
398            continue;
399        }
400        if ch == '"' {
401            in_quotes = !in_quotes;
402            continue;
403        }
404        if in_quotes {
405            continue;
406        }
407        let lower = ch.to_ascii_lowercase();
408        if matches!(lower, 'y' | 'd' | 'h' | 's') {
409            return true;
410        }
411        if lower == 'm' {
412            return true;
413        }
414    }
415    false
416}
417
418fn format_date_time(value: f64, format: &str) -> String {
419    let int_part = value.floor() as i64;
420    let frac = value.fract().abs();
421    let rounded_seconds = (frac * 86_400.0).round() as u64;
422    let day_carry = rounded_seconds / 86_400;
423    let total_seconds = rounded_seconds % 86_400;
424    let mut hours = (total_seconds / 3600) as u32;
425    let minutes = ((total_seconds % 3600) / 60) as u32;
426    let seconds = (total_seconds % 60) as u32;
427    let subsec_frac = (frac * 86_400.0) - (total_seconds as f64);
428
429    // Excel dates end at serial 2958465 (9999-12-31); larger or non-finite
430    // serials would overflow chrono arithmetic inside `serial_to_date`.
431    let date_opt = if value.is_finite() && value < 2_958_466.0 {
432        serial_to_date(int_part as f64 + day_carry as f64)
433    } else {
434        None
435    };
436    let (year, month, day) = if let Some(date) = date_opt {
437        (date.year() as u32, date.month(), date.day())
438    } else {
439        (1900, 1, 1)
440    };
441
442    let has_ampm = {
443        let lower = format.to_ascii_lowercase();
444        lower.contains("am/pm") || lower.contains("a/p")
445    };
446
447    let mut ampm_str = "";
448    if has_ampm {
449        if hours == 0 {
450            hours = 12;
451            ampm_str = "AM";
452        } else if hours < 12 {
453            ampm_str = "AM";
454        } else if hours == 12 {
455            ampm_str = "PM";
456        } else {
457            hours -= 12;
458            ampm_str = "PM";
459        }
460    }
461
462    let month_names_short = [
463        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
464    ];
465    let month_names_long = [
466        "January",
467        "February",
468        "March",
469        "April",
470        "May",
471        "June",
472        "July",
473        "August",
474        "September",
475        "October",
476        "November",
477        "December",
478    ];
479
480    let mut result = String::with_capacity(format.len() * 2);
481    let chars: Vec<char> = format.chars().collect();
482    let len = chars.len();
483    let mut i = 0;
484    let mut in_quotes = false;
485
486    while i < len {
487        let ch = chars[i];
488
489        if ch == '"' {
490            in_quotes = !in_quotes;
491            i += 1;
492            continue;
493        }
494        if in_quotes {
495            result.push(ch);
496            i += 1;
497            continue;
498        }
499        if ch == '\\' && i + 1 < len {
500            result.push(chars[i + 1]);
501            i += 2;
502            continue;
503        }
504
505        // Skip padding/spacing characters: _ followed by a character
506        if ch == '_' && i + 1 < len {
507            result.push(' ');
508            i += 2;
509            continue;
510        }
511        // Skip * repetition fill
512        if ch == '*' && i + 1 < len {
513            i += 2;
514            continue;
515        }
516
517        // Elapsed time brackets [h], [mm], and [ss] represent the complete
518        // signed duration rather than a clock component.
519        if ch == '[' {
520            if let Some((unit_seconds, end)) = elapsed_bracket_token(&chars, i) {
521                let elapsed_seconds = (value * 86_400.0).round() as i64;
522                result.push_str(&(elapsed_seconds / unit_seconds).to_string());
523                i = end;
524                continue;
525            }
526        }
527
528        let lower = ch.to_ascii_lowercase();
529
530        if lower == 'y' {
531            let count = count_char(&chars, i, 'y');
532            if count <= 2 {
533                result.push_str(&format!("{:02}", year % 100));
534            } else {
535                result.push_str(&format!("{:04}", year));
536            }
537            i += count;
538            continue;
539        }
540
541        if lower == 'm' {
542            let count = count_char(&chars, i, 'm');
543            if is_m_minute_context(&chars, i) {
544                // Minutes
545                if count == 1 {
546                    result.push_str(&format!("{}", minutes));
547                } else {
548                    result.push_str(&format!("{:02}", minutes));
549                }
550            } else {
551                // Month
552                match count {
553                    1 => result.push_str(&format!("{}", month)),
554                    2 => result.push_str(&format!("{:02}", month)),
555                    3 => {
556                        if (1..=12).contains(&month) {
557                            result.push_str(month_names_short[(month - 1) as usize]);
558                        }
559                    }
560                    4 => {
561                        if (1..=12).contains(&month) {
562                            result.push_str(month_names_long[(month - 1) as usize]);
563                        }
564                    }
565                    _ => {
566                        result.push_str(&format!("{:02}", month));
567                    }
568                }
569            }
570            i += count;
571            continue;
572        }
573
574        if lower == 'd' {
575            let count = count_char(&chars, i, 'd');
576            match count {
577                1 => result.push_str(&format!("{}", day)),
578                2 => result.push_str(&format!("{:02}", day)),
579                3 => {
580                    if let Some(date) = date_opt {
581                        let day_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
582                        let wd = date.weekday().num_days_from_monday() as usize;
583                        result.push_str(day_names[wd]);
584                    }
585                }
586                _ => {
587                    if let Some(date) = date_opt {
588                        let day_names = [
589                            "Monday",
590                            "Tuesday",
591                            "Wednesday",
592                            "Thursday",
593                            "Friday",
594                            "Saturday",
595                            "Sunday",
596                        ];
597                        let wd = date.weekday().num_days_from_monday() as usize;
598                        result.push_str(day_names[wd]);
599                    }
600                }
601            }
602            i += count;
603            continue;
604        }
605
606        if lower == 'h' {
607            let count = count_char(&chars, i, 'h');
608            if count == 1 {
609                result.push_str(&format!("{}", hours));
610            } else {
611                result.push_str(&format!("{:02}", hours));
612            }
613            i += count;
614            continue;
615        }
616
617        if lower == 's' {
618            let count = count_char(&chars, i, 's');
619            if count == 1 {
620                result.push_str(&format!("{}", seconds));
621            } else {
622                result.push_str(&format!("{:02}", seconds));
623            }
624            i += count;
625            continue;
626        }
627
628        // AM/PM or A/P
629        if lower == 'a' {
630            if i + 4 < len {
631                let slice: String = chars[i..i + 5].iter().collect();
632                if slice.eq_ignore_ascii_case("AM/PM") {
633                    result.push_str(ampm_str);
634                    i += 5;
635                    continue;
636                }
637            }
638            if i + 2 < len {
639                let slice: String = chars[i..i + 3].iter().collect();
640                if slice.eq_ignore_ascii_case("A/P") {
641                    if ampm_str == "AM" {
642                        result.push('A');
643                    } else {
644                        result.push('P');
645                    }
646                    i += 3;
647                    continue;
648                }
649            }
650            result.push(ch);
651            i += 1;
652            continue;
653        }
654
655        if ch == '.' && i + 1 < len && chars[i + 1] == '0' {
656            // Fractional seconds
657            result.push('.');
658            let count = count_char(&chars, i + 1, '0');
659            let sub = subsec_frac.abs();
660            let digits = format!("{:.*}", count, sub);
661            // digits is like "0.xxx", take the part after '.'
662            if let Some(dot_pos) = digits.find('.') {
663                result.push_str(&digits[dot_pos + 1..]);
664            }
665            i += 1 + count;
666            continue;
667        }
668
669        // Pass through separators and other literal characters
670        result.push(ch);
671        i += 1;
672    }
673
674    result
675}
676
677fn elapsed_bracket_token(chars: &[char], start: usize) -> Option<(i64, usize)> {
678    let token = chars.get(start + 1)?.to_ascii_lowercase();
679    let unit_seconds = match token {
680        'h' => 3_600,
681        'm' => 60,
682        's' => 1,
683        _ => return None,
684    };
685    let count = count_char(chars, start + 1, token);
686    let end = start + 1 + count;
687    (chars.get(end) == Some(&']')).then_some((unit_seconds, end + 1))
688}
689
690/// Determine whether an 'm' token at position `pos` in the format chars
691/// should be interpreted as minutes (true) or months (false).
692/// Minutes if there is a preceding 'h' or a following 's' (skipping separators).
693fn is_m_minute_context(chars: &[char], pos: usize) -> bool {
694    // Look backwards for 'h', skipping ':', ' ', digits, brackets
695    let mut j = pos;
696    while j > 0 {
697        j -= 1;
698        let c = chars[j].to_ascii_lowercase();
699        if c == 'h' {
700            return true;
701        }
702        if c == ':' || c == ' ' || c == ']' || c == '[' {
703            continue;
704        }
705        break;
706    }
707    // Look forwards past the 'm' run for 's', skipping ':', ' ', digits, '.'
708    let m_count = count_char(chars, pos, 'm');
709    let mut k = pos + m_count;
710    while k < chars.len() {
711        let c = chars[k].to_ascii_lowercase();
712        if c == 's' {
713            return true;
714        }
715        if c == ':' || c == ' ' || c == '0' || c == '.' {
716            k += 1;
717            continue;
718        }
719        break;
720    }
721    false
722}
723
724fn count_char(chars: &[char], start: usize, target: char) -> usize {
725    let lower_target = target.to_ascii_lowercase();
726    let mut count = 0;
727    let mut i = start;
728    while i < chars.len() && chars[i].to_ascii_lowercase() == lower_target {
729        count += 1;
730        i += 1;
731    }
732    count
733}
734
735fn format_numeric(value: f64, format: &str) -> String {
736    let is_negative = value < 0.0;
737    let abs_val = value.abs();
738
739    // Parse the format to understand: digit placeholders, decimal places,
740    // comma grouping, percent, underscore/star padding, and literal text.
741    let has_percent = format_has_unquoted_char(format, '%');
742    let display_val = if has_percent {
743        abs_val * 100.0
744    } else {
745        abs_val
746    };
747
748    // Count decimal places from the format
749    let decimal_places = count_decimal_places(format);
750    let required_decimal_places = count_required_decimal_places(format);
751
752    // Check for thousands separator (comma grouping)
753    let has_comma_grouping = has_thousands_separator(format);
754
755    // Check for trailing commas (divide by 1000 per comma)
756    let trailing_comma_count = count_trailing_commas(format);
757    let display_val = display_val / 1000f64.powi(trailing_comma_count as i32);
758
759    // Round to the number of decimal places
760    let rounded = if decimal_places > 0 {
761        let factor = 10f64.powi(decimal_places as i32);
762        (display_val * factor).round() / factor
763    } else {
764        display_val.round()
765    };
766
767    let int_part = rounded.trunc() as u64;
768    let frac_part =
769        ((rounded - rounded.trunc()).abs() * 10f64.powi(decimal_places as i32)).round() as u64;
770
771    // Format integer part
772    let int_str = format!("{}", int_part);
773    let int_display = if has_comma_grouping {
774        add_thousands_separators(&int_str)
775    } else {
776        int_str.clone()
777    };
778
779    // Count required integer digits (from '0' placeholders in integer part)
780    let min_int_digits = count_integer_zeros(format);
781    let padded_int = if int_display.len() < min_int_digits && int_part == 0 {
782        let needed = min_int_digits - int_display.len();
783        let mut s = "0".repeat(needed);
784        s.push_str(&int_display);
785        if has_comma_grouping {
786            add_thousands_separators(&s)
787        } else {
788            s
789        }
790    } else {
791        int_display
792    };
793
794    // Build the output by walking through the format pattern
795    // For simplicity, output the formatted number with appropriate decorations
796    let mut output = String::with_capacity(format.len() + 10);
797    let chars: Vec<char> = format.chars().collect();
798    let len = chars.len();
799    let mut i = 0;
800    let mut in_quotes = false;
801    let mut number_placed = false;
802    let emit_minus = is_negative && !has_explicit_negative_presentation(format);
803
804    while i < len {
805        let ch = chars[i];
806
807        if ch == '"' {
808            in_quotes = !in_quotes;
809            i += 1;
810            continue;
811        }
812        if in_quotes {
813            output.push(ch);
814            i += 1;
815            continue;
816        }
817        if ch == '\\' && i + 1 < len {
818            output.push(chars[i + 1]);
819            i += 2;
820            continue;
821        }
822        if ch == '_' && i + 1 < len {
823            output.push(' ');
824            i += 2;
825            continue;
826        }
827        if ch == '*' && i + 1 < len {
828            i += 2;
829            continue;
830        }
831
832        if (ch == '0' || ch == '#' || ch == ',') && !number_placed {
833            // Find the end of the numeric pattern
834            let num_end = find_numeric_end(&chars, i);
835            // Place the formatted number
836            let num_str = format_decimal_number(
837                &padded_int,
838                frac_part,
839                decimal_places,
840                required_decimal_places,
841            );
842
843            if emit_minus {
844                output.push('-');
845            }
846            output.push_str(&num_str);
847            number_placed = true;
848            i = num_end;
849            continue;
850        }
851
852        if ch == '.' && !number_placed {
853            // This dot is part of the numeric pattern, handle together
854            i += 1;
855            continue;
856        }
857
858        if ch == '%' {
859            output.push('%');
860            i += 1;
861            continue;
862        }
863
864        if ch == '(' || ch == ')' || ch == '-' || ch == '+' || ch == ' ' || ch == ':' || ch == '/' {
865            output.push(ch);
866            i += 1;
867            continue;
868        }
869
870        if ch == '0' || ch == '#' || ch == ',' || ch == '.' {
871            i += 1;
872            continue;
873        }
874
875        output.push(ch);
876        i += 1;
877    }
878
879    // If no number was placed, check whether the format actually has digit placeholders.
880    // Formats like `"-"` (pure literal text) should not emit a number at all.
881    if !number_placed {
882        let has_digit_placeholder = format.chars().any(|c| c == '0' || c == '#');
883        if has_digit_placeholder {
884            if emit_minus {
885                output.push('-');
886            }
887            output.push_str(&format_decimal_number(
888                &padded_int,
889                frac_part,
890                decimal_places,
891                required_decimal_places,
892            ));
893        }
894    }
895
896    output
897}
898
899fn format_decimal_number(
900    integer: &str,
901    fraction: u64,
902    decimal_places: usize,
903    required_decimal_places: usize,
904) -> String {
905    if decimal_places == 0 {
906        return integer.to_string();
907    }
908
909    let mut fraction = format!("{fraction:0>decimal_places$}");
910    while fraction.len() > required_decimal_places && fraction.ends_with('0') {
911        fraction.pop();
912    }
913    if fraction.is_empty() {
914        integer.to_string()
915    } else {
916        format!("{integer}.{fraction}")
917    }
918}
919
920fn has_explicit_negative_presentation(format: &str) -> bool {
921    let mut in_quotes = false;
922    let mut escaped = false;
923    for ch in format.chars() {
924        if escaped {
925            escaped = false;
926            continue;
927        }
928        if ch == '\\' {
929            escaped = true;
930        } else if ch == '"' {
931            in_quotes = !in_quotes;
932        } else if !in_quotes && matches!(ch, '-' | '(') {
933            return true;
934        }
935    }
936    false
937}
938
939fn format_has_unquoted_char(format: &str, target: char) -> bool {
940    let mut in_quotes = false;
941    let mut prev_backslash = false;
942    for ch in format.chars() {
943        if prev_backslash {
944            prev_backslash = false;
945            continue;
946        }
947        if ch == '\\' {
948            prev_backslash = true;
949            continue;
950        }
951        if ch == '"' {
952            in_quotes = !in_quotes;
953            continue;
954        }
955        if !in_quotes && ch == target {
956            return true;
957        }
958    }
959    false
960}
961
962fn count_decimal_places(format: &str) -> usize {
963    let mut in_quotes = false;
964    let mut prev_backslash = false;
965    let mut found_dot = false;
966    let mut count = 0;
967
968    for ch in format.chars() {
969        if prev_backslash {
970            prev_backslash = false;
971            continue;
972        }
973        if ch == '\\' {
974            prev_backslash = true;
975            continue;
976        }
977        if ch == '"' {
978            in_quotes = !in_quotes;
979            continue;
980        }
981        if in_quotes {
982            continue;
983        }
984        if ch == '.' && !found_dot {
985            found_dot = true;
986            continue;
987        }
988        if found_dot && (ch == '0' || ch == '#') {
989            count += 1;
990        } else if found_dot && ch != '0' && ch != '#' {
991            break;
992        }
993    }
994    count
995}
996
997fn count_required_decimal_places(format: &str) -> usize {
998    let mut in_quotes = false;
999    let mut escaped = false;
1000    let mut found_dot = false;
1001    let mut count = 0;
1002
1003    for ch in format.chars() {
1004        if escaped {
1005            escaped = false;
1006            continue;
1007        }
1008        if ch == '\\' {
1009            escaped = true;
1010            continue;
1011        }
1012        if ch == '"' {
1013            in_quotes = !in_quotes;
1014            continue;
1015        }
1016        if in_quotes {
1017            continue;
1018        }
1019        if ch == '.' && !found_dot {
1020            found_dot = true;
1021        } else if found_dot && ch == '0' {
1022            count += 1;
1023        } else if found_dot && ch != '#' {
1024            break;
1025        }
1026    }
1027    count
1028}
1029
1030fn has_thousands_separator(format: &str) -> bool {
1031    let mut in_quotes = false;
1032    let mut prev_backslash = false;
1033    let chars: Vec<char> = format.chars().collect();
1034
1035    for (i, &ch) in chars.iter().enumerate() {
1036        if prev_backslash {
1037            prev_backslash = false;
1038            continue;
1039        }
1040        if ch == '\\' {
1041            prev_backslash = true;
1042            continue;
1043        }
1044        if ch == '"' {
1045            in_quotes = !in_quotes;
1046            continue;
1047        }
1048        if in_quotes {
1049            continue;
1050        }
1051        // A comma is a thousands separator if it appears between digit placeholders
1052        if ch == ',' {
1053            let has_digit_before = chars[..i].iter().rev().any(|&c| c == '0' || c == '#');
1054            let has_digit_after = chars[i + 1..].iter().any(|&c| c == '0' || c == '#');
1055            if has_digit_before && has_digit_after {
1056                return true;
1057            }
1058        }
1059    }
1060    false
1061}
1062
1063fn count_trailing_commas(format: &str) -> usize {
1064    let mut in_quotes = false;
1065    let mut prev_backslash = false;
1066    let chars: Vec<char> = format.chars().collect();
1067    let mut count = 0;
1068
1069    // Find the last digit placeholder, then count commas after it
1070    let mut last_digit_pos = None;
1071    for (i, &ch) in chars.iter().enumerate() {
1072        if prev_backslash {
1073            prev_backslash = false;
1074            continue;
1075        }
1076        if ch == '\\' {
1077            prev_backslash = true;
1078            continue;
1079        }
1080        if ch == '"' {
1081            in_quotes = !in_quotes;
1082            continue;
1083        }
1084        if in_quotes {
1085            continue;
1086        }
1087        if ch == '0' || ch == '#' {
1088            last_digit_pos = Some(i);
1089        }
1090    }
1091
1092    if let Some(pos) = last_digit_pos {
1093        for &ch in &chars[pos + 1..] {
1094            if ch == ',' {
1095                count += 1;
1096            } else {
1097                break;
1098            }
1099        }
1100    }
1101    count
1102}
1103
1104fn count_integer_zeros(format: &str) -> usize {
1105    let mut in_quotes = false;
1106    let mut prev_backslash = false;
1107    let mut count = 0;
1108    let mut found_dot = false;
1109
1110    for ch in format.chars() {
1111        if prev_backslash {
1112            prev_backslash = false;
1113            continue;
1114        }
1115        if ch == '\\' {
1116            prev_backslash = true;
1117            continue;
1118        }
1119        if ch == '"' {
1120            in_quotes = !in_quotes;
1121            continue;
1122        }
1123        if in_quotes {
1124            continue;
1125        }
1126        if ch == '.' {
1127            found_dot = true;
1128            continue;
1129        }
1130        if !found_dot && ch == '0' {
1131            count += 1;
1132        }
1133    }
1134    count
1135}
1136
1137fn add_thousands_separators(s: &str) -> String {
1138    let bytes = s.as_bytes();
1139    let len = bytes.len();
1140    if len <= 3 {
1141        return s.to_string();
1142    }
1143    let mut result = String::with_capacity(len + len / 3);
1144    let remainder = len % 3;
1145    if remainder > 0 {
1146        result.push_str(&s[..remainder]);
1147        if len > remainder {
1148            result.push(',');
1149        }
1150    }
1151    for (i, chunk) in s.as_bytes()[remainder..].chunks(3).enumerate() {
1152        if i > 0 {
1153            result.push(',');
1154        }
1155        result.push_str(std::str::from_utf8(chunk).unwrap_or(""));
1156    }
1157    result
1158}
1159
1160fn find_numeric_end(chars: &[char], start: usize) -> usize {
1161    let mut i = start;
1162    let mut in_quotes = false;
1163    while i < chars.len() {
1164        let ch = chars[i];
1165        if ch == '"' {
1166            in_quotes = !in_quotes;
1167            i += 1;
1168            continue;
1169        }
1170        if in_quotes {
1171            i += 1;
1172            continue;
1173        }
1174        if ch == '0' || ch == '#' || ch == ',' || ch == '.' {
1175            i += 1;
1176        } else {
1177            break;
1178        }
1179    }
1180    i
1181}
1182
1183fn format_scientific(value: f64, format: &str) -> String {
1184    let decimal_places = count_decimal_places(format);
1185    let integer_placeholders = scientific_integer_placeholders(format);
1186    let engineering = integer_placeholders > 1;
1187    let abs = value.abs();
1188    let mut exp = if abs == 0.0 {
1189        0
1190    } else {
1191        abs.log10().floor() as i32
1192    };
1193    if engineering {
1194        exp = exp.div_euclid(3) * 3;
1195    }
1196    let mut mantissa = if abs == 0.0 {
1197        0.0
1198    } else {
1199        abs / 10f64.powi(exp)
1200    };
1201    let limit = if engineering {
1202        10f64.powi(integer_placeholders as i32)
1203    } else {
1204        10.0
1205    };
1206    let factor = 10f64.powi(decimal_places as i32);
1207    mantissa = (mantissa * factor).round() / factor;
1208    if mantissa >= limit {
1209        mantissa /= if engineering { 1_000.0 } else { 10.0 };
1210        exp += if engineering { 3 } else { 1 };
1211    }
1212    let mantissa = format!("{:.*}", decimal_places, mantissa);
1213
1214    // Count the '0' digits after E+/E- in the format to determine exponent width
1215    let exp_width = count_exponent_zeros(format).max(1);
1216
1217    // Determine sign character for exponent
1218    let has_plus = format.contains("E+") || format.contains("e+");
1219    let exp_sign = if exp >= 0 {
1220        if has_plus {
1221            "+"
1222        } else {
1223            ""
1224        }
1225    } else {
1226        "-"
1227    };
1228
1229    let exp_display = format!(
1230        "{}{:0>width$}",
1231        exp_sign,
1232        exp.unsigned_abs(),
1233        width = exp_width
1234    );
1235
1236    let sign = if value < 0.0 { "-" } else { "" };
1237
1238    // Determine E vs e
1239    let e_char = if format.contains('e') { 'e' } else { 'E' };
1240
1241    format!("{}{}{}{}", sign, mantissa, e_char, exp_display)
1242}
1243
1244fn scientific_integer_placeholders(format: &str) -> usize {
1245    let e_pos = format
1246        .char_indices()
1247        .find_map(|(i, ch)| matches!(ch, 'E' | 'e').then_some(i))
1248        .unwrap_or(format.len());
1249    format[..e_pos]
1250        .split_once('.')
1251        .map_or(&format[..e_pos], |(integer, _)| integer)
1252        .chars()
1253        .filter(|ch| matches!(ch, '0' | '#'))
1254        .count()
1255        .max(1)
1256}
1257
1258fn count_exponent_zeros(format: &str) -> usize {
1259    // Search the original bytes with ASCII matching so the offset stays valid
1260    // for `format`; Unicode case mapping can change byte lengths.
1261    let find_marker = |sign: u8| {
1262        format
1263            .as_bytes()
1264            .windows(2)
1265            .position(|pair| pair[0].eq_ignore_ascii_case(&b'E') && pair[1] == sign)
1266    };
1267    if let Some(pos) = find_marker(b'+').or_else(|| find_marker(b'-')) {
1268        let after = &format[pos + 2..];
1269        after.chars().take_while(|&c| c == '0').count()
1270    } else {
1271        2
1272    }
1273}
1274
1275fn format_fraction(value: f64, format: &str) -> String {
1276    // Fractions only make sense for finite values whose whole part fits i64;
1277    // anything else renders as a plain number, matching Excel's fallback.
1278    if !value.is_finite() || value.abs() >= i64::MAX as f64 {
1279        return format_general(value);
1280    }
1281    let abs = value.abs();
1282    let mut whole = abs.floor() as i64;
1283    let frac = abs - whole as f64;
1284
1285    let sign = if value < 0.0 { "-" } else { "" };
1286
1287    if frac < 1e-10 {
1288        if format.contains('#') {
1289            return format!("{}{}", sign, whole);
1290        }
1291        return format!("{}{}    ", sign, whole);
1292    }
1293
1294    let (mut num, den) = if let Some(den) = fixed_fraction_denominator(format) {
1295        (((frac * den as f64).round() as u64).min(den), den)
1296    } else {
1297        let denom_q_count = format
1298            .split('/')
1299            .nth(1)
1300            .map(|s| s.chars().filter(|&c| c == '?').count())
1301            .unwrap_or(1);
1302        let max_denom = match denom_q_count {
1303            0 | 1 => 9,
1304            2 => 99,
1305            3 => 999,
1306            _ => 9999,
1307        };
1308        best_fraction(frac, max_denom)
1309    };
1310
1311    if num == den {
1312        whole = whole.saturating_add(1);
1313        num = 0;
1314    }
1315
1316    let has_whole = format.contains('#');
1317
1318    if num == 0 {
1319        return format!("{}{}", sign, whole);
1320    }
1321
1322    if has_whole {
1323        if whole > 0 {
1324            format!("{}{} {}/{}", sign, whole, num, den)
1325        } else {
1326            format!("{}{}/{}", sign, num, den)
1327        }
1328    } else {
1329        match (whole as u64)
1330            .checked_mul(den)
1331            .and_then(|product| product.checked_add(num))
1332        {
1333            Some(total_num) => format!("{}{}/{}", sign, total_num, den),
1334            None => format!("{}{} {}/{}", sign, whole, num, den),
1335        }
1336    }
1337}
1338
1339fn fixed_fraction_denominator(format: &str) -> Option<u64> {
1340    // Excel accepts at most a five-digit literal denominator.
1341    const MAX_FIXED_DENOMINATOR: u64 = 99_999;
1342    let denominator = format.split_once('/')?.1;
1343    let digits: String = denominator
1344        .chars()
1345        .take_while(|ch| ch.is_ascii_digit())
1346        .collect();
1347    let den: u64 = digits.parse().ok()?;
1348    (1..=MAX_FIXED_DENOMINATOR).contains(&den).then_some(den)
1349}
1350
1351fn best_fraction(value: f64, max_denom: u64) -> (u64, u64) {
1352    if value <= 0.0 {
1353        return (0, 1);
1354    }
1355    let mut best_num = 0u64;
1356    let mut best_den = 1u64;
1357    let mut best_err = value.abs();
1358
1359    for den in 1..=max_denom {
1360        let num = (value * den as f64).round() as u64;
1361        if num == 0 {
1362            continue;
1363        }
1364        let err = (value - num as f64 / den as f64).abs();
1365        if err < best_err {
1366            best_err = err;
1367            best_num = num;
1368            best_den = den;
1369        }
1370        if best_err < 1e-10 {
1371            break;
1372        }
1373    }
1374    (best_num, best_den)
1375}
1376
1377use chrono::Datelike;
1378
1379#[cfg(test)]
1380#[allow(clippy::approx_constant)]
1381mod tests {
1382    use super::*;
1383
1384    #[test]
1385    fn test_builtin_format_code_general() {
1386        assert_eq!(builtin_format_code(0), Some("General"));
1387    }
1388
1389    #[test]
1390    fn test_builtin_format_code_integer() {
1391        assert_eq!(builtin_format_code(1), Some("0"));
1392    }
1393
1394    #[test]
1395    fn test_builtin_format_code_decimal() {
1396        assert_eq!(builtin_format_code(2), Some("0.00"));
1397    }
1398
1399    #[test]
1400    fn test_builtin_format_code_thousands() {
1401        assert_eq!(builtin_format_code(3), Some("#,##0"));
1402    }
1403
1404    #[test]
1405    fn test_builtin_format_code_date() {
1406        assert_eq!(builtin_format_code(14), Some("m/d/yyyy"));
1407    }
1408
1409    #[test]
1410    fn test_builtin_format_code_text() {
1411        assert_eq!(builtin_format_code(49), Some("@"));
1412    }
1413
1414    #[test]
1415    fn test_builtin_format_code_unknown() {
1416        assert_eq!(builtin_format_code(100), None);
1417        assert_eq!(builtin_format_code(50), None);
1418    }
1419
1420    #[test]
1421    fn test_format_general_zero() {
1422        assert_eq!(format_number(0.0, "General"), "0");
1423    }
1424
1425    #[test]
1426    fn test_format_general_integer() {
1427        assert_eq!(format_number(42.0, "General"), "42");
1428        assert_eq!(format_number(-100.0, "General"), "-100");
1429    }
1430
1431    #[test]
1432    fn test_format_general_decimal() {
1433        assert_eq!(format_number(3.14, "General"), "3.14");
1434    }
1435
1436    #[test]
1437    fn test_format_general_large_number() {
1438        assert_eq!(format_number(1000000.0, "General"), "1000000");
1439    }
1440
1441    #[test]
1442    fn test_format_integer() {
1443        assert_eq!(format_number(42.0, "0"), "42");
1444        assert_eq!(format_number(42.7, "0"), "43");
1445        assert_eq!(format_number(0.0, "0"), "0");
1446    }
1447
1448    #[test]
1449    fn test_format_decimal_2() {
1450        assert_eq!(format_number(3.14159, "0.00"), "3.14");
1451        assert_eq!(format_number(3.0, "0.00"), "3.00");
1452        assert_eq!(format_number(0.5, "0.00"), "0.50");
1453    }
1454
1455    #[test]
1456    fn test_format_decimal_without_integer_placeholder() {
1457        assert_eq!(format_number(0.5, ".00"), "0.50");
1458    }
1459
1460    #[test]
1461    fn test_format_negative_elapsed_hours() {
1462        assert_eq!(format_number(-1.5, "[h]:mm"), "-36:00");
1463    }
1464
1465    #[test]
1466    fn test_format_elapsed_bracket_tokens() {
1467        assert_eq!(format_number(1.5, "[h]"), "36");
1468        assert_eq!(format_number(1.5, "[mm]"), "2160");
1469        assert_eq!(format_number(1.5, "[ss]"), "129600");
1470        assert_eq!(format_number(-1.5, "[mm]"), "-2160");
1471    }
1472
1473    #[test]
1474    fn test_format_thousands() {
1475        assert_eq!(format_number(1234.0, "#,##0"), "1,234");
1476        assert_eq!(format_number(1234567.0, "#,##0"), "1,234,567");
1477        assert_eq!(format_number(999.0, "#,##0"), "999");
1478        assert_eq!(format_number(0.0, "#,##0"), "0");
1479    }
1480
1481    #[test]
1482    fn test_format_thousands_decimal() {
1483        assert_eq!(format_number(1234.56, "#,##0.00"), "1,234.56");
1484        assert_eq!(format_number(0.0, "#,##0.00"), "0.00");
1485    }
1486
1487    #[test]
1488    fn test_format_percent() {
1489        assert_eq!(format_number(0.75, "0%"), "75%");
1490        assert_eq!(format_number(0.5, "0%"), "50%");
1491        assert_eq!(format_number(1.0, "0%"), "100%");
1492    }
1493
1494    #[test]
1495    fn test_format_percent_decimal() {
1496        assert_eq!(format_number(0.7534, "0.00%"), "75.34%");
1497        assert_eq!(format_number(0.5, "0.00%"), "50.00%");
1498    }
1499
1500    #[test]
1501    fn test_format_scientific() {
1502        let result = format_number(1234.5, "0.00E+00");
1503        assert_eq!(result, "1.23E+03");
1504    }
1505
1506    #[test]
1507    fn test_format_scientific_small() {
1508        let result = format_number(0.001, "0.00E+00");
1509        assert_eq!(result, "1.00E-03");
1510    }
1511
1512    #[test]
1513    fn test_format_engineering_notation_and_exponent_width() {
1514        assert_eq!(format_number(12_345.0, "##0.0E+0"), "12.3E+3");
1515        assert_eq!(format_number(0.0123, "##0.0E+0"), "12.3E-3");
1516        assert_eq!(format_number(12_345.0, "0.0E+000"), "1.2E+004");
1517    }
1518
1519    #[test]
1520    fn test_format_date_mdy() {
1521        // 2024-01-15 = serial 45306
1522        let serial =
1523            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 1, 15).unwrap());
1524        assert_eq!(format_number(serial, "m/d/yyyy"), "1/15/2024");
1525    }
1526
1527    #[test]
1528    fn test_format_date_dmy() {
1529        let serial =
1530            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 3, 5).unwrap());
1531        assert_eq!(format_number(serial, "d-mmm-yy"), "5-Mar-24");
1532    }
1533
1534    #[test]
1535    fn test_format_date_dm() {
1536        let serial =
1537            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 6, 15).unwrap());
1538        assert_eq!(format_number(serial, "d-mmm"), "15-Jun");
1539    }
1540
1541    #[test]
1542    fn test_format_date_my() {
1543        let serial =
1544            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 12, 1).unwrap());
1545        assert_eq!(format_number(serial, "mmm-yy"), "Dec-24");
1546    }
1547
1548    #[test]
1549    fn test_format_time_hm_ampm() {
1550        let serial = crate::cell::datetime_to_serial(
1551            chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
1552                .unwrap()
1553                .and_hms_opt(14, 30, 0)
1554                .unwrap(),
1555        );
1556        assert_eq!(format_number(serial, "h:mm AM/PM"), "2:30 PM");
1557    }
1558
1559    #[test]
1560    fn test_format_time_hm_ampm_morning() {
1561        let serial = crate::cell::datetime_to_serial(
1562            chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
1563                .unwrap()
1564                .and_hms_opt(9, 5, 0)
1565                .unwrap(),
1566        );
1567        assert_eq!(format_number(serial, "h:mm AM/PM"), "9:05 AM");
1568    }
1569
1570    #[test]
1571    fn test_format_time_hms() {
1572        let serial = crate::cell::datetime_to_serial(
1573            chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
1574                .unwrap()
1575                .and_hms_opt(14, 30, 45)
1576                .unwrap(),
1577        );
1578        assert_eq!(format_number(serial, "h:mm:ss"), "14:30:45");
1579    }
1580
1581    #[test]
1582    fn test_format_time_rounding_carries_to_next_day() {
1583        let serial =
1584            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap())
1585                + (86_399.5 / 86_400.0);
1586        assert_eq!(
1587            format_number(serial, "m/d/yyyy h:mm:ss"),
1588            "1/2/2024 0:00:00"
1589        );
1590    }
1591
1592    #[test]
1593    fn test_format_time_hm_24h() {
1594        let serial = crate::cell::datetime_to_serial(
1595            chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
1596                .unwrap()
1597                .and_hms_opt(14, 30, 0)
1598                .unwrap(),
1599        );
1600        assert_eq!(format_number(serial, "h:mm"), "14:30");
1601    }
1602
1603    #[test]
1604    fn test_format_datetime_combined() {
1605        let serial = crate::cell::datetime_to_serial(
1606            chrono::NaiveDate::from_ymd_opt(2024, 1, 15)
1607                .unwrap()
1608                .and_hms_opt(14, 30, 0)
1609                .unwrap(),
1610        );
1611        assert_eq!(format_number(serial, "m/d/yyyy h:mm"), "1/15/2024 14:30");
1612    }
1613
1614    #[test]
1615    fn test_format_date_yyyy_mm_dd() {
1616        let serial =
1617            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 6, 15).unwrap());
1618        assert_eq!(format_number(serial, "yyyy-mm-dd"), "2024-06-15");
1619    }
1620
1621    #[test]
1622    fn test_format_date_dd_mm_yyyy() {
1623        let serial =
1624            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 6, 15).unwrap());
1625        assert_eq!(format_number(serial, "dd/mm/yyyy"), "15/06/2024");
1626    }
1627
1628    #[test]
1629    fn test_format_text_passthrough() {
1630        assert_eq!(format_number(42.0, "@"), "42");
1631    }
1632
1633    #[test]
1634    fn test_format_multi_section_positive_negative() {
1635        assert_eq!(format_number(42.0, "#,##0;-#,##0"), "42");
1636        assert_eq!(format_number(-42.0, "#,##0;-#,##0"), "-42");
1637    }
1638
1639    #[test]
1640    fn test_format_multi_section_three_parts() {
1641        assert_eq!(format_number(42.0, "#,##0;-#,##0;\"zero\""), "42");
1642        assert_eq!(format_number(-42.0, "#,##0;-#,##0;\"zero\""), "-42");
1643    }
1644
1645    #[test]
1646    fn test_format_color_stripped() {
1647        assert_eq!(format_number(42.0, "[Red]0"), "42");
1648        assert_eq!(format_number(42.0, "[Blue]0.00"), "42.00");
1649    }
1650
1651    #[test]
1652    fn test_format_with_builtin_general() {
1653        assert_eq!(format_with_builtin(42.0, 0), Some("42".to_string()));
1654    }
1655
1656    #[test]
1657    fn test_format_with_builtin_percent() {
1658        assert_eq!(format_with_builtin(0.5, 9), Some("50%".to_string()));
1659    }
1660
1661    #[test]
1662    fn test_format_with_builtin_unknown() {
1663        assert_eq!(format_with_builtin(42.0, 100), None);
1664    }
1665
1666    #[test]
1667    fn test_format_fraction_simple() {
1668        let result = format_number(1.5, "# ?/?");
1669        assert_eq!(result, "1 1/2");
1670    }
1671
1672    #[test]
1673    fn test_format_fraction_two_digit() {
1674        let result = format_number(0.333, "# ??/??");
1675        // Should approximate to something close to 1/3
1676        assert!(result.contains("/"), "result was: {}", result);
1677    }
1678
1679    #[test]
1680    fn test_format_fraction_fixed_denominator() {
1681        assert_eq!(format_number(1.25, "# ?/8"), "1 2/8");
1682        assert_eq!(format_number(0.125, "?/16"), "2/16");
1683    }
1684
1685    #[test]
1686    fn test_format_fraction_extreme_inputs_do_not_panic() {
1687        // Values beyond i64 and user denominators near u64::MAX must not overflow.
1688        for (value, format) in [
1689            (42949672964294967296.0, "/?"),
1690            (1.5, "?/18446744073709551615"),
1691            (f64::MAX, "# ?/?"),
1692            (-1.0e19, "?/??"),
1693            (f64::INFINITY, "?/?"),
1694            (f64::NAN, "?/?"),
1695            (1.5, "?/0"),
1696        ] {
1697            let rendered = format_number(value, format);
1698            assert!(!rendered.is_empty(), "{value} {format}");
1699        }
1700        // A zero or oversized literal denominator falls back to the best fraction.
1701        assert_eq!(format_number(1.5, "# ?/0"), "1 1/2");
1702        assert_eq!(format_number(1.5, "# ?/18446744073709551615"), "1 1/2");
1703        assert_eq!(format_number(0.5, "?/18446744073709551615"), "1/2");
1704    }
1705
1706    #[test]
1707    fn test_format_optional_fractional_digits() {
1708        assert_eq!(format_number(1.2, "0.##"), "1.2");
1709        assert_eq!(format_number(1.0, "0.##"), "1");
1710        assert_eq!(format_number(1.2, "0.0#"), "1.2");
1711    }
1712
1713    #[test]
1714    fn test_format_negative_in_parens() {
1715        let result = format_number(-1234.0, "#,##0_);(#,##0)");
1716        assert!(result.contains("1,234"), "result was: {}", result);
1717        assert!(result.contains("("), "result was: {}", result);
1718    }
1719
1720    #[test]
1721    fn test_format_empty_format_uses_general() {
1722        assert_eq!(format_number(42.0, ""), "42");
1723    }
1724
1725    #[test]
1726    fn test_format_date_long_month() {
1727        let serial =
1728            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 1, 15).unwrap());
1729        assert_eq!(format_number(serial, "d mmmm yyyy"), "15 January 2024");
1730    }
1731
1732    #[test]
1733    fn test_format_time_ampm_midnight() {
1734        let serial =
1735            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
1736        // Midnight = no fractional part
1737        assert_eq!(format_number(serial, "h:mm AM/PM"), "12:00 AM");
1738    }
1739
1740    #[test]
1741    fn test_format_time_ampm_noon() {
1742        let serial = crate::cell::datetime_to_serial(
1743            chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
1744                .unwrap()
1745                .and_hms_opt(12, 0, 0)
1746                .unwrap(),
1747        );
1748        assert_eq!(format_number(serial, "h:mm AM/PM"), "12:00 PM");
1749    }
1750
1751    #[test]
1752    fn test_format_builtin_mmss() {
1753        let serial = crate::cell::datetime_to_serial(
1754            chrono::NaiveDate::from_ymd_opt(2024, 1, 1)
1755                .unwrap()
1756                .and_hms_opt(0, 5, 30)
1757                .unwrap(),
1758        );
1759        assert_eq!(format_number(serial, "mm:ss"), "05:30");
1760    }
1761
1762    #[test]
1763    fn test_format_general_negative_decimal() {
1764        let result = format_number(-3.14, "General");
1765        assert_eq!(result, "-3.14");
1766    }
1767
1768    #[test]
1769    fn test_format_date_two_digit_year() {
1770        let serial =
1771            crate::cell::date_to_serial(chrono::NaiveDate::from_ymd_opt(2024, 6, 15).unwrap());
1772        assert_eq!(format_number(serial, "yy"), "24");
1773    }
1774
1775    #[test]
1776    fn test_format_thousands_separator_with_zero() {
1777        assert_eq!(add_thousands_separators("0"), "0");
1778        assert_eq!(add_thousands_separators("100"), "100");
1779        assert_eq!(add_thousands_separators("1000"), "1,000");
1780        assert_eq!(add_thousands_separators("1000000"), "1,000,000");
1781    }
1782
1783    #[test]
1784    fn test_parse_sections_single() {
1785        let sections = parse_sections("0.00");
1786        assert_eq!(sections, vec!["0.00"]);
1787    }
1788
1789    #[test]
1790    fn test_parse_sections_multi() {
1791        let sections = parse_sections("0.00;-0.00;\"zero\"");
1792        assert_eq!(sections, vec!["0.00", "-0.00", "\"zero\""]);
1793    }
1794
1795    #[test]
1796    fn test_parse_sections_quoted_semicolon() {
1797        let sections = parse_sections("\"a;b\"");
1798        assert_eq!(sections, vec!["\"a;b\""]);
1799    }
1800
1801    #[test]
1802    fn test_strip_color() {
1803        let (cleaned, color) = strip_color_and_condition("[Red]0.00");
1804        assert_eq!(cleaned, "0.00");
1805        assert_eq!(color, Some("Red".to_string()));
1806    }
1807
1808    #[test]
1809    fn test_strip_condition() {
1810        let (cleaned, _) = strip_color_and_condition("[>100]0.00");
1811        assert_eq!(cleaned, "0.00");
1812    }
1813
1814    #[test]
1815    fn test_is_date_time_format_checks() {
1816        assert!(is_date_time_format("yyyy-mm-dd"));
1817        assert!(is_date_time_format("h:mm:ss"));
1818        assert!(is_date_time_format("m/d/yyyy"));
1819        assert!(!is_date_time_format("0.00"));
1820        assert!(!is_date_time_format("#,##0"));
1821        assert!(!is_date_time_format("\"yyyy\"0"));
1822    }
1823
1824    #[test]
1825    fn test_count_decimal_places_none() {
1826        assert_eq!(count_decimal_places("0"), 0);
1827        assert_eq!(count_decimal_places("#,##0"), 0);
1828    }
1829
1830    #[test]
1831    fn test_count_decimal_places_two() {
1832        assert_eq!(count_decimal_places("0.00"), 2);
1833        assert_eq!(count_decimal_places("#,##0.00"), 2);
1834    }
1835
1836    #[test]
1837    fn test_count_decimal_places_three() {
1838        assert_eq!(count_decimal_places("0.000"), 3);
1839    }
1840
1841    #[test]
1842    fn test_parse_condition_operators() {
1843        let c = parse_condition(">100").unwrap();
1844        assert_eq!(c.op, ConditionOp::Gt);
1845        assert_eq!(c.threshold, 100.0);
1846
1847        let c = parse_condition(">=50").unwrap();
1848        assert_eq!(c.op, ConditionOp::Ge);
1849        assert_eq!(c.threshold, 50.0);
1850
1851        let c = parse_condition("<1000").unwrap();
1852        assert_eq!(c.op, ConditionOp::Lt);
1853        assert_eq!(c.threshold, 1000.0);
1854
1855        let c = parse_condition("<=0").unwrap();
1856        assert_eq!(c.op, ConditionOp::Le);
1857        assert_eq!(c.threshold, 0.0);
1858
1859        let c = parse_condition("=0").unwrap();
1860        assert_eq!(c.op, ConditionOp::Eq);
1861        assert_eq!(c.threshold, 0.0);
1862
1863        let c = parse_condition("<>5").unwrap();
1864        assert_eq!(c.op, ConditionOp::Ne);
1865        assert_eq!(c.threshold, 5.0);
1866
1867        let c = parse_condition("!=5").unwrap();
1868        assert_eq!(c.op, ConditionOp::Ne);
1869        assert_eq!(c.threshold, 5.0);
1870
1871        assert!(parse_condition("Red").is_none());
1872        assert!(parse_condition("").is_none());
1873    }
1874
1875    #[test]
1876    fn test_condition_matches() {
1877        let c = Condition {
1878            op: ConditionOp::Gt,
1879            threshold: 100.0,
1880        };
1881        assert!(c.matches(150.0));
1882        assert!(!c.matches(100.0));
1883        assert!(!c.matches(50.0));
1884    }
1885
1886    #[test]
1887    fn test_conditional_two_sections_color_and_condition() {
1888        // [Red][>100]0;[Blue][<=100]0
1889        let fmt = "[Red][>100]0;[Blue][<=100]0";
1890        assert_eq!(format_number(150.0, fmt), "150");
1891        assert_eq!(format_number(50.0, fmt), "50");
1892        assert_eq!(format_number(100.0, fmt), "100");
1893    }
1894
1895    #[test]
1896    fn test_conditional_three_sections_cascading() {
1897        // [>1000]#,##0;[>100]0.0;0.00
1898        let fmt = "[>1000]#,##0;[>100]0.0;0.00";
1899        assert_eq!(format_number(5000.0, fmt), "5,000");
1900        assert_eq!(format_number(500.0, fmt), "500.0");
1901        assert_eq!(format_number(50.0, fmt), "50.00");
1902    }
1903
1904    #[test]
1905    fn test_conditional_equals_zero() {
1906        // [=0]"zero";General -- value 0 matches first section, value 42 falls through
1907        let fmt = "[=0]\"zero\";0";
1908        assert_eq!(format_number(0.0, fmt), "zero");
1909        assert_eq!(format_number(42.0, fmt), "42");
1910    }
1911
1912    #[test]
1913    fn test_conditional_with_sign_format() {
1914        // [Red][>0]+0;[Blue][<0]-0;0
1915        let fmt = "[Red][>0]+0;[Blue][<0]-0;0";
1916        assert_eq!(format_number(5.0, fmt), "+5");
1917        assert_eq!(format_number(-3.0, fmt), "-3");
1918        assert_eq!(format_number(0.0, fmt), "0");
1919    }
1920
1921    #[test]
1922    fn test_conditional_section_preserves_or_formats_negative_sign_once() {
1923        assert_eq!(format_number(-3.0, "[<0]0;0"), "-3");
1924        assert_eq!(format_number(-3.0, "[<0]-0;0"), "-3");
1925        assert_eq!(format_number(-3.0, "[<0](0);0"), "(3)");
1926    }
1927
1928    #[test]
1929    fn test_extract_condition_from_section() {
1930        let cond = extract_condition("[Red][>100]0.00").unwrap();
1931        assert_eq!(cond.op, ConditionOp::Gt);
1932        assert_eq!(cond.threshold, 100.0);
1933
1934        let cond = extract_condition("[<=0]0");
1935        assert!(cond.is_some());
1936        assert_eq!(cond.unwrap().op, ConditionOp::Le);
1937
1938        assert!(extract_condition("[Red]0.00").is_none());
1939        assert!(extract_condition("0.00").is_none());
1940    }
1941}