Skip to main content

predict_sdk/
utils.rs

1use rust_decimal::Decimal;
2
3/// Round a decimal to N significant digits
4///
5/// This matches the TypeScript SDK's `toSignificantDigits` function
6pub fn round_to_significant_digits(value: Decimal, sig_figs: u32) -> Decimal {
7    if value.is_zero() {
8        return Decimal::ZERO;
9    }
10
11    let abs_value = value.abs();
12
13    // Convert to string to count significant digits
14    let str_value = abs_value.to_string();
15
16    // Count all digits
17    let all_digits: String = str_value.chars().filter(|c| c.is_ascii_digit()).collect();
18    let total_digits = all_digits.len();
19
20    // If we already have fewer digits than sig_figs, return as-is
21    if total_digits <= sig_figs as usize {
22        return value;
23    }
24
25    // Calculate how many digits to keep
26    let excess = total_digits - sig_figs as usize;
27    let divisor = Decimal::from(10_i64.pow(excess as u32));
28
29    // Divide, round, then multiply back
30    let truncated = (abs_value / divisor).floor() * divisor;
31
32    if value.is_sign_negative() {
33        -truncated
34    } else {
35        truncated
36    }
37}
38
39// Tests are in integration tests