Skip to content

<f64 as FromStr> produces incorrect results in some cases #23505

Closed

Description

@JRoush

In at least one case (and presumably more), FromStr::from_str() produces a result that is off by one ulp.

Example:

pub fn main() {
    use std::str::FromStr;    
    let literal: f64 = 0.123f64;
    let fromstr: f64 = FromStr::from_str("0.123").unwrap();
    println!("Literal: {:16X}", as_int(literal)); // Literal: 3FBF7CED916872B0
    println!("FromStr: {:16X}", as_int(fromstr)); // FromStr: 3FBF7CED916872B1
    println!("Equal: {}", literal == fromstr);    // Equal: false
}

pub fn as_int(f: f64) -> u64 {
    unsafe{ std::mem::transmute::<f64,u64>(f) }
}

Here the compiler produces the correct result for the literal value but the runtime parsing function produces a different, incorrect result. The difference is tiny, but of course it is enough to cause problems :)

For the record, here is the output of rustc --version --verbose on my system:

rustc 1.0.0-nightly (30e1f9a1c 2015-03-14) (built 2015-03-15)
binary: rustc
commit-hash: 30e1f9a1c2bf7134135800bc9afd082773defadc
commit-date: 2015-03-14
build-date: 2015-03-15
host: x86_64-unknown-linux-gnu
release: 1.0.0-nightly

Activity

  1. lifthrasiir commented on Mar 19, 2015

    @lifthrasiir
    Contributor

    I assume this is a duplicate of #7648. We have really hairy decimal to floating point routine right now.

  2. JRoush commented on Mar 19, 2015

    @JRoush
    Author

    @lifthrasiir Whoops, looks like you are right.

  3. steveklabnik commented on Mar 19, 2015

    @steveklabnik
    Contributor

    closing as duplicate

  4. added a commit that references this issue on Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions