Open mrhdias opened 1 month ago
So it's rounding correctly but we probably want a special formatting filter for floats.
The solution really involves making a filter.
use tera::{Result, Value};
use std::collections::HashMap;
// Register the custom filter
// tera.register_filter("round_and_format", round_and_format_filter);
fn round_and_format_filter(value: &Value, params: &HashMap<String, Value>) -> Result<Value> {
let num = value.as_f64().ok_or_else(|| tera::Error::msg("Filter can only be applied to numbers"))?;
let decimal_places = params.get("places")
.and_then(Value::as_u64)
.ok_or_else(|| tera::Error::msg("Filter parameter 'places' is required and must be a positive integer"))?;
Ok(Value::String(format!("{:.1$}", num, decimal_places as usize)))
}
Example of usage:
<span class="regular_price">${{ product.price | round_and_format(places=2) }}</span>
I created a template to show a list of products with prices, but I wanted all prices to have two decimal places. To do this I used the Built-in filter round, but it doesn't work as expected if the variable is f32 and the decimal places are 00 instead of $XX.00 it puts $XX or if it is $XX.10 put $XX.1!
Does anyone have an idea of how I can always put two decimal places in prices?