How to convert a decimal to i64 in Rust

1 Answer

0 votes
/*
    ============================================================
    Convert a decimal-like value to i64 in Rust.

    This program demonstrates:
      • Conversion using f64::round(), which rounds to the nearest integer.
      • Conversion using f64::trunc(), which truncates toward zero.
      • Conversion using "as i64", which also truncates.
      • A helper function that prints both results for comparison.

    Notes:
      • Rust does not have a built-in decimal type.
      • f64 is used for decimal values.
      • round() returns an f64; cast to i64 afterward.
      • trunc() removes the fractional part.
    ============================================================
*/

fn convert_decimal_to_i64(value: f64) -> i64 {
    // Rounds to nearest integer, then cast to i64
    value.round() as i64
}

fn cast_decimal_to_i64(value: f64) -> i64 {
    // Truncates fractional part toward zero
    value as i64
}

fn show_conversions(value: f64) {
    println!("Input decimal: {:.4}", value);

    let rounded = convert_decimal_to_i64(value);
    let truncated = cast_decimal_to_i64(value);

    println!("Rounded (round): {}", rounded);
    println!("Truncated (as i64): {}", truncated);
    println!();
}

fn main() {
    // Example values to demonstrate behavior
    show_conversions(12.7);
    show_conversions(12.3);
    show_conversions(-5.8);
    show_conversions(42.0); // already an integer
}


/*
run:

Input decimal: 12.7000
Rounded (round): 13
Truncated (as i64): 12

Input decimal: 12.3000
Rounded (round): 12
Truncated (as i64): 12

Input decimal: -5.8000
Rounded (round): -6
Truncated (as i64): -5

Input decimal: 42.0000
Rounded (round): 42
Truncated (as i64): 42

*/

 



answered Aug 6 by avibootz
edited Aug 6 by avibootz
...