How to check whether a floating-point variable is an integer (has no fractional part) in Rust

1 Answer

0 votes
// -----------------------------------------------------------------------------
// Demonstrates how to check whether a floating‑point value (f64) is an integer.
// Uses a small tolerance to safely handle floating‑point precision issues.
// Rust's f64 behaves like a double in many languages.
// -----------------------------------------------------------------------------

fn is_integer(value: f64) -> bool {
    // A tiny tolerance helps avoid floating‑point precision errors.
    const EPSILON: f64 = 1e-12;

    // floor() returns the largest integer <= value.
    let floored = value.floor();

    // If the absolute difference is extremely small, treat the number as integer.
    (value - floored).abs() < EPSILON
}

// -----------------------------------------------------------------------------
// Prints a descriptive message for the given floating‑point value.
// -----------------------------------------------------------------------------
fn print_check(value: f64) {
    println!("Checking value: {:.15}", value);

    if is_integer(value) {
        println!("Result: The value contains an integer.\n");
    } else {
        println!("Result: The value contains a floating‑point number.\n");
    }
}

// -----------------------------------------------------------------------------
// Entry point demonstrating several example values.
// -----------------------------------------------------------------------------
fn main() {
    // Example input values (Rust f64 behaves like a double)
    let a: f64 = 42.0;                 // integer-like
    let b: f64 = 42.00000000001;       // floating-point due to tiny fraction
    let c: f64 = 89.0000000000001;     // integer-like
    let d: f64 = -7.0;                 // negative integer-like
    let e: f64 = 3.14;                 // floating-point

    // Run checks
    print_check(a);
    print_check(b);
    print_check(c);
    print_check(d);
    print_check(e);
}



/*
run:

Checking value: 42.000000000000000
Result: The value contains an integer.

Checking value: 42.000000000009997
Result: The value contains a floating‑point number.

Checking value: 89.000000000000099
Result: The value contains an integer.

Checking value: -7.000000000000000
Result: The value contains an integer.

Checking value: 3.140000000000000
Result: The value contains a floating‑point number.

*/

 



answered Sep 10 by avibootz

Related questions

...