if i pass the value to json! macro via method, it prints the value with decimal points which the original data has not
fn main() {
let val = 219.83;
t(val);
}
fn t(v: f32) {
let j = serde_json::json!({"val":v});
let s = serde_json::to_string(&j).unwrap();
println!("{s}");
}
the output string is
{"val":219.8300018310547}
if i pass the value to json! macro no problem
fn main() {
let val = 219.83;
let j = serde_json::json!({"val":val});
let s = serde_json::to_string(&j).unwrap();
println!("{s}");
}
I suspect that's because in the second let val = 219.83 the compiler will infer that val's type is f64 (float literals are f64 by default), but when you do t(val) it'll infer that you actually wanted a f32.
That means you are actually comparing the difference between json!({ "val": 219.83_f32 }) and json!({ "val": 219.83_f64 }).
arbitrary_precision won't change it to 219.83. 219.8300018310547 is a more accurate representation of 219.83_f32 than 219.83. 219.83 would be less accurate.
If the difference between 219.83 and 219.8300018310547 is important to you then perhaps you shouldn't be using f32. f32 is not capable of representing 219.83 exactly (and neither is f64).
To be more explicit, if your numeric types will have at most 2 decimal places (e.g. some currencies) then you can use an integer type to store the hundredths instead.