Skip to content

Number loses precision on f32s #1004

@Gelbpunkt

Description

@Gelbpunkt

Hi there, I've gone through a couple of issues but haven't found anything that quite matches my problem, so if this is a duplicate, feel free to close this and direct me elsewhere :)

The following small snippet replicates my issue:

use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Deserialize, Serialize, Debug, Clone)]
struct Test(f32);

fn main() {
    let a = Test(5.55);
    let value = serde_json::to_value(a.clone()).unwrap();
    println!("{value:?}");
    let serialized = serde_json::to_string(&value).unwrap();
    println!("{serialized}");
    let serialized = serde_json::to_string(&a).unwrap();
    println!("{serialized}");
}

// Number(5.550000190734863)
// 5.550000190734863
// 5.55

I would expect the serialized values to be identical (and serialized to 5.55), but they aren't. This happens both with and without arbitrary_precision and float_roundtrip enabled. I would've expected this to be precisely 5.55, especially with arbitrary_precision enabled. When changing the type to an f64, it works as expected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions