【问题标题】:How to convert f64 into String and parse back into f64?如何将 f64 转换为 String 并解析回 f64?
【发布时间】:2021-02-20 20:53:38
【问题描述】:
let s = format!("{}", t);
let x = s.parse::<f64>();

如果t 的类型为f64,是否存在解析回f64 会失败的情况?

【问题讨论】:

  • 你的意思是它必须解析为与== 真实比较的东西吗?或者只是解析永远不会是Err?因为 NaN != NaN 以浮动开头。
  • 第二个。

标签: string parsing serialization rust numbers


【解决方案1】:

似乎不是这样。该程序涵盖了所有有趣的边缘情况,例如NaN、Infinity、Negative Infinity 等,它编译和运行都很好,没有恐慌:

fn check_serialization_eq(nums: &[f64]) {
    for num in nums {
        let s = num.to_string();
        let x = s.parse::<f64>().unwrap();
        dbg!(num, x);
    }
}

fn main() {
    check_serialization_eq(&[
        f64::MIN,
        f64::MAX,
        f64::NAN,
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::EPSILON,
    ]);
}

playground

【讨论】:

  • 请注意,Rust 的 stdlib 的 previous versions 会发出无法往返的字符串表示。可能仍然存在边缘情况,如果可能,我会选择不依赖这种行为。
  • 另外,不要忘记,一般来说,比较浮动数字是很棘手的,即使是看起来很规则的数字!此外,还有多种不同的NaNs/infinities。
猜你喜欢
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
  • 2020-02-16
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 2022-07-02
  • 1970-01-01
相关资源
最近更新 更多