There's no documented way to losslessly print a float (so it will be parsed as the exact same value)
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
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:
- An integer .N: (...)
- An integer or name followed by dollar sign .N$: (...)
- 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)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked std::fmt precision documentation and the f32 primitive documentation, then verify what guarantees are stated for {} and {:.} float formatting. Done means the documentation clearly identifies an official lossless-roundtrip approach, or explicitly explains that no such guarantee exists.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100