Skip to main content

luaur_code_gen/functions/
format_g.rs

1extern crate alloc;
2
3use alloc::format;
4use alloc::string::String;
5
6pub(crate) fn format_g(v: f64, precision: i32) -> String {
7    if v.is_nan() {
8        return String::from("nan");
9    }
10
11    if v.is_infinite() {
12        return if v.is_sign_negative() {
13            String::from("-inf")
14        } else {
15            String::from("inf")
16        };
17    }
18
19    if v == 0.0 {
20        return if v.is_sign_negative() {
21            String::from("-0")
22        } else {
23            String::from("0")
24        };
25    }
26
27    let sci = format!("{:.*e}", (precision - 1).max(0) as usize, v);
28    let exp: i32 = sci[sci.find('e').map(|i| i + 1).unwrap_or(sci.len())..]
29        .parse()
30        .unwrap_or(0);
31
32    if exp >= -4 && exp < precision {
33        let frac = (precision - 1 - exp).max(0) as usize;
34        let mut s = format!("{:.*}", frac, v);
35
36        if s.contains('.') {
37            while s.ends_with('0') {
38                s.pop();
39            }
40            if s.ends_with('.') {
41                s.pop();
42            }
43        }
44
45        s
46    } else {
47        let (mant, exp_part) = sci.split_once('e').unwrap_or((sci.as_str(), "0"));
48        let mut m = String::from(mant);
49
50        if m.contains('.') {
51            while m.ends_with('0') {
52                m.pop();
53            }
54            if m.ends_with('.') {
55                m.pop();
56            }
57        }
58
59        let e: i32 = exp_part.parse().unwrap_or(0);
60        format!("{}e{}{:02}", m, if e < 0 { "-" } else { "+" }, e.abs())
61    }
62}