iliana / rust-crowbar

Wrapper to simplify writing AWS Lambda functions in Rust (using the Python execution environment)
https://docs.rs/crowbar
Apache License 2.0
197 stars 16 forks source link

Incorrect conversion of json with float values. #25

Closed shmuga closed 6 years ago

shmuga commented 6 years ago

Hello,

I'm new to Rust and not sure if I choose correct repo to report you a problem but I found a problem with passing JSON from Rust to Lambda response.

Using such code snippet in Rust println! shows 45.74 but in aws response I have { "val": 45.7400016784668 }. Maybe it's Python problem?

#[macro_use(lambda)]
extern crate crowbar;
#[macro_use]
extern crate cpython;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;

#[derive(Debug,Serialize)]
struct WithNumber {
    val: f32,
}

lambda!(|event, context| {
    let initial_str = "45.74";
    let obj = WithNumber { val: initial_str.parse::<f32>().unwrap() };
    println!("{:?}", obj); // prints WithNmber { val: 45.74 }
    Ok(serde_json::to_value(&obj)?)
});
euank commented 6 years ago

I think this is a rust thing unrelated to crowbar or python or lambda. Even with the debug format string, rust doesn't print the full precision of a floating point number.

If you run this playground, you'll see those extra digits of precision are there in rust too if you look for them.

I think the confusion is entirely from rust's f32 display and debug implementation both implicitly rounding floating point numbers for printing by default.

shmuga commented 6 years ago

Heh, thanks a lot, anyway! I thinks this issue could be closed.