Relatively new to Rust. I am trying to make an API call which requires the JSON body to be serialized.
The JSON body contains an order_amount key with value which can only take values having INR format 100.36, i.e. Rupees 100 and paise 36. Some more examples 10.48, 3.20, 1.09.
The problem I'm facing is that after serialization with json!() from serde_json, the floating point value becomes something like 100.359765464332.
The API subsequently fails because it expects the order_amount to have only two decimal places.
Here is the code that I have:
The imports
use lambda_runtime::{handler_fn, Context, Error};
use reqwest::header::ACCEPT;
use reqwest::{Response, StatusCode};
use serde_json::json;
use std::env;
#[macro_use]
extern crate serde_derive;
The struct that I'm serializing
#[derive(Serialize, Deserialize, Clone, Debug)]
struct OrderCreationEvent {
order_amount: f32,
customer_details: ...,
order_meta: ...,
}
Eg. The order_amount here has a value of 15.38
async fn so_my_function(
e: OrderCreationEvent,
_c: Context,
) -> std::result::Result<CustomOutput, Error> {
let resp: Response = client
.post(url)
.json::<serde_json::Value>(&json!(e))
.send()
.await?;
After json!(), the amount is being serialized to 15.379345234542. I require 15.38
I read a few articles about writing a custom serializer for f32 which can truncate to 2 decimals, but my proficiency is limited in Rust.
So, I found this code and have been tinkering at it with no luck:
fn order_amount_serializer<S>(x: &f32, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_f32(*x)
// Ok(f32::trunc(x * 100.0) / 100.0)
}
Whether or not the custom serializer is the right approach or solution to the problem, I would still like to learn how to write one, so feel free to enlighten me there too. Cheers! :)