Given u64
number u64value: u64
. How can it be lossy converted into f64
? Will u64value as f64
always work?
Asked
Active
Viewed 1,418 times
1

k_rus
- 2,959
- 1
- 19
- 31
-
Yes, it will always work. Why not? – Chayim Friedman Feb 21 '23 at 09:05
-
Because I haven't found documentation of how `as` works in this case. – k_rus Feb 21 '23 at 09:31
-
1Now I reached the documentation page from the answer: https://doc.rust-lang.org/1.49.0/reference/expressions/operator-expr.html#type-cast-expressions – k_rus Feb 21 '23 at 09:33
1 Answers
1
Since you explicitly stated « lossy », there is no problem.
If the original u64
value is quite big, you will lose some lower bits due to the limited precision of the f64
.
See the reference about the type cast expressions with as
.
(see also this answer)
fn main() {
let u64value: u64 = 123_456_789_123_456_789;
let f64value: f64 = u64value as f64;
let u64back: u64 = f64value as u64;
println!("u64value: {:?}", u64value);
println!("f64value: {:?}", f64value);
println!("u64back: {:?}", u64back);
println!("delta: {:?}", u64value - u64back);
}
/*
u64value: 123456789123456789
f64value: 1.2345678912345678e17
u64back: 123456789123456784
delta: 5
*/

prog-fh
- 13,492
- 1
- 15
- 30
-
You can even use `let u64value: u64 = u64::MAX` to make sure `u64` fits into `f64`. – denis.peplin Feb 21 '23 at 09:39
-
1@denis.peplin unfortunately, with `u64::MAX` nothing is lost since the obtained `f64` does not use its mantissa (except the implicit leading 1); everything is expressed in the exponent. See for example [this converter](https://www.h-schmidt.net/FloatConverter/IEEE754.html) with `f32`/`u32::MAX`(4294967295). – prog-fh Feb 21 '23 at 09:53
-
@prog-fh Can you add direct link to rust documentation, which explains semantics of `as` on numerics? I found it by following a link, which was mentioned in the answer you linked (too many indirections). (e.g., https://doc.rust-lang.org/1.49.0/reference/expressions/operator-expr.html#type-cast-expressions) – k_rus Feb 22 '23 at 17:22