diff --git a/crates/toml/src/value.rs b/crates/toml/src/value.rs index e52e5a6a..c8065a6c 100644 --- a/crates/toml/src/value.rs +++ b/crates/toml/src/value.rs @@ -921,7 +921,9 @@ impl ser::Serializer for ValueSerializer { } fn serialize_f32(self, value: f32) -> Result { - self.serialize_f64(value.into()) + // Preserve sign of NaN. The `as` produces a nondeterministic sign. + let sign = if value.is_sign_positive() { 1.0 } else { -1.0 }; + self.serialize_f64((value as f64).copysign(sign)) } fn serialize_f64(self, value: f64) -> Result { diff --git a/crates/toml_edit/src/ser/value.rs b/crates/toml_edit/src/ser/value.rs index 808bb900..f250d63d 100644 --- a/crates/toml_edit/src/ser/value.rs +++ b/crates/toml_edit/src/ser/value.rs @@ -105,7 +105,9 @@ impl serde::ser::Serializer for ValueSerializer { } fn serialize_f32(self, v: f32) -> Result { - self.serialize_f64(v as f64) + // Preserve sign of NaN. The `as` produces a nondeterministic sign. + let sign = if v.is_sign_positive() { 1.0 } else { -1.0 }; + self.serialize_f64((v as f64).copysign(sign)) } fn serialize_f64(self, v: f64) -> Result {