Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does f32 not implement std::fmt::Binary?

Tags:

rust

I am trying to display a f32 in binary format:

let value: f32 = 0.45;
let my_string = format!("{:b}", value);

I get the following error: "the trait bound f32: std::fmt::Binary is not satisfied".

I think we have to implement the trait by ourselves when we want to have a binary representation of a f32 into a String. In fact, Rust doesn't know what to do for some f32 values that cannot be represented in binary. For example, what to do with 0.1 ? Should the trait return the string 0.00011 or 0.0001100110011? Is this the reason why there is no definition of std::fmt::Binary for f32?

like image 257
jean553 Avatar asked Jul 05 '26 05:07

jean553


1 Answers

The documentation for std::fmt::Binary provides a hint:

The alternate flag, #, adds a 0b in front of the output.

Basically, for every numerical literal expression in Rust, there is a formatter that can print it. If f32 were to implement std::fmt::Binary, this could be seen as making an opinionated statement on what binary floating point literals should look like, even when the language itself doesn't support them and quite possibly never will.

In the early pre-1.0 days there was actually an experimental syntax extension for hexadecimal floating point literals that was removed before 1.0 stabilization. Occasionally there is still some discussion of the issue, but no plans for adding it to the language, let alone its binary cousin.

like image 128
bug Avatar answered Jul 06 '26 21:07

bug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!