Skip to content

There's no documented way to losslessly print a float (so it will be parsed as the exact same value) #128972

Open
@maia-s

Description

@maia-s

I have a use case where I need to output a floating point number (either a f32 or a f64) into a generated Rust source file as text, which needs to be parsed by Rust as the original floating point number exactly. I did some searching and found out about the {:.} format to print a floating point number with "all available precision". This seems to work, but according to the documentation for fmt, this isn't a valid formatting specifier. The documentation states:

There are three possible ways to specify the desired precision:

  1. An integer .N: (...)
  2. An integer or name followed by dollar sign .N$: (...)
  3. An asterisk .*: (...)

Additionally, printing a float with {} seems to print the same thing as with {:.}, at least for the floats I've tried, but as far as I can tell the precision of this isn't documented either. The documentation says that "printing floats with println and friends will often discard insignificant digits", which kind of suggests that it won't discard significant digits, but it doesn't actually say that, so I don't know if I can rely on it for a lossless roundtrip.

Is this a documentation issue, or is there no official way to print a float losslessly? (The floats I generate must be usable in const on stable, so I can't use from_bits, but I suppose transmute would work as an alternative)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsA-floating-pointArea: Floating point numbers and arithmeticE-needs-investigationCall for partcipation: This issues needs some investigation to determine current statusT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions