Floating point (f32) within a struct renders incorrecly
Something is going wrong with floating point precision when rendering values inside a struct.
It works to render just the f32 value, and just to double check it also works to use rusts format implementation on the nested value.
But rendering nested struct value with hbs fails. The last assertion in this test fails with:
assertion left == right failed
left: "0.800000011920929"
right: "0.8"
#[test]
fn renders_nested_f32() {
let hbs = Handlebars::new();
let rendered_backoff_multiplicative = hbs
.render_template(
"{{backoff_multiplicative}}",
&json!({"backoff_multiplicative": 0.8}),
)
.unwrap();
assert_eq!(&rendered_backoff_multiplicative, "0.8");
let sync_config = SyncConfig {
initial_block_interval: 10_000,
backoff_multiplicative: 0.8,
acceleration_additive: 2_000,
interval_ceiling: 10_000,
backoff_millis: 5000,
query_timeout_millis: 20_000,
};
assert_eq!(sync_config.backoff_multiplicative.to_string(), "0.8");
let rendered_backoff_multiplicative = hbs
.render_template(
"{{backoff_multiplicative}}",
&json!({"backoff_multiplicative": sync_config.backoff_multiplicative}),
)
.unwrap();
//only this assertion fails
assert_eq!(&rendered_backoff_multiplicative, "0.8");
}
Hello @JonoPrest That's how floating point numbers work. You hardly get a very precise one. Typically you can use a format string like "{:.2}" for that
Hello @JonoPrest That's how floating point numbers work. You hardly get a very precise one. Typically you can use a format string like "{:.2}" for that
Hey @sunng87 I understand that's how they work but why is the rendering in hbs giving "0.800000011920929" while standard rust fmt implementation gives "0.8" on the same number? And why does it only do it when rendering from a struct and not just a standalone f32?
Seems like a weird behaviour for rendering to me.