How to get the first digit of a float number in Rust

1 Answer

0 votes
use std::f64;

/*
    Returns the first digit of a floating‑point number.

    Approach:
    - Convert the number to a string using to_string().
    - Trim whitespace.
    - If the number is negative, skip the leading '-' sign.
    - Read the first numeric character.
    - Convert that character back into an integer.

    This avoids math‑based digit counting, which can be unreliable with floats.
*/
fn get_first_digit(value: f64) -> u32 {
    // Convert the number to a trimmed string representation
    let text: String = value.to_string().trim().to_string();

    // Handle negative numbers by skipping the leading '-'
    let first_char: char = if text.starts_with('-') {
        text.chars().nth(1).unwrap()
    } else {
        text.chars().nth(0).unwrap()
    };

    // Convert the character to a digit
    first_char.to_digit(10).unwrap()
}

/*
    Main program.
*/
fn main() {
    let f: f64 = 376.287152;

    let first_digit: u32 = get_first_digit(f);

    println!("{}", first_digit);
}


/*
run:

3

*/

 



answered Sep 15 by avibootz
...