如何将`f64`将其转换为`f32`?
如何将f64
转换为最近的f32
?
从> tryfrom 实现中既没有,这可能是因为此类实现仅用于无损转换。我还搜索了
f64
文档中的f32
的引用,反之亦然,没有发现。
let double: f64 = 0.;
// doesn't work
// let single: f32 = double.into();
// let single: f32 = double.try_into().unwrap();
How can I convert a f64
into the closest f32
?
There is neither a From
nor a TryFrom
implementation, presumably because such implementations are only provided for lossless conversions. I also searched for references to f32
in the f64
docs and vice versa, and found nothing.
let double: f64 = 0.;
// doesn't work
// let single: f32 = double.into();
// let single: f32 = double.try_into().unwrap();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,我们可以将
用作铸造的关键字。整数转换通常不需要,因为“从较大的整数到较小的整数(例如U32 - u8)将截断”,通常不想要这一点。对于
f64
f32
,它非常明智:“恐慌而是最简单的解决方案可能是检查
is_finite
:In this case, we can use the
as
keyword for casting. It is usually not desired for integer conversions because "casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate", and this is usually not wanted. Forf64
tof32
, however, it's very sensible:If an overflow to infinity is not desired and you want to panic instead, the simplest solution might be to check for
is_finite
: