std-method

Duration::try_from_secs_f64 and try_from_secs_f32

Use fallible conversion for externally supplied numerical durations. Negative values, NaN, infinity and unrepresentable values produce an error rather than a panic. Expected stdout (not executed): 500 ms invalid invalid invalid Common mistake: Checking only whether a floating number is less than zero; NaN needs handling too.

Formal Syntax & Structure

rust syntaxrust
Duration::try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>

Working Example

Example Snippetrust
fn main() {    use std::time::Duration;    for x in [0.5, -1.0, f64::NAN, f64::INFINITY] {        match Duration::try_from_secs_f64(x) {            Ok(d) => println!("{} ms", d.as_millis()),            Err(_) => println!("invalid"),        }    }}
Rust Reference