Skip to content

Duration::from_secs_f32 gives wrong results #90225

Closed
@manio

Description

@manio

Hello.
I am diagnosing why I've got a wrong duration computed from Duration::from_secs_f32()...

I tried this code:

let val1 = Duration::from_secs_f32(30.0);
println!("{}", format_duration(val1).to_string());

I expected to see an exact 30-second duration.
Instead, I've got this:
"30s 1us 24ns"
which is: 30 seconds and 1024 nanos.

I dig deeper into rust code and I've prepared a sample code which is computing it based on the rust/time.rs source code:

    let secs: f32 = 30.0;
    const NANOS_PER_SEC: u32 = 1_000_000_000;
    let nanos = secs * (NANOS_PER_SEC as f32);
    let nanos = nanos as u128;
    let s = (nanos / (NANOS_PER_SEC as u128)) as u64;
    let nano = (nanos % (NANOS_PER_SEC as u128)) as u32;
    let secs = Duration::new(s, nano);
    println!("sec={}, nanos={}", s, nano);

As the result I've got:
sec=30, nanos=1024

Instead of exact 30 seconds and 0 nanos.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions