Skip to content

Commit

Permalink
Add float filter
Browse files Browse the repository at this point in the history
  • Loading branch information
youmouse committed Nov 3, 2018
1 parent 7dce5de commit 9e38c63
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion askama_shared/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ use escaping::{self, MarkupDisplay};
// Askama or should refer to a local `filters` module. It should contain all the
// filters shipped with Askama, even the optional ones (since optional inclusion
// in the const vector based on features seems impossible right now).
pub const BUILT_IN_FILTERS: [&str; 20] = [
pub const BUILT_IN_FILTERS: [&str; 21] = [
"abs",
"capitalize",
"center",
"e",
"escape",
"float",
"format",
"indent",
"int",
Expand Down Expand Up @@ -77,6 +78,14 @@ where
escape(i)
}

/// Casts number to f32
pub fn float<T>(number: T) -> Result<f32>
where
T: NumCast,
{
number.to_f32().ok_or(Fmt(fmt::Error))
}

/// Formats arguments according to the specified format
///
/// The first argument to this filter must be a string literal (as in normal
Expand Down Expand Up @@ -259,6 +268,15 @@ mod tests {
use super::*;
use std::f32::INFINITY;

#[test]
fn test_float() {
assert_eq!(float(1).unwrap(), 1.0 as f32);
assert_eq!(float(1.9).unwrap(), 1.9 as f32);
assert_eq!(float(-1.9).unwrap(), -1.9 as f32);
assert_eq!(float(INFINITY as f64).unwrap(), INFINITY);
assert_eq!(float(-INFINITY as f64).unwrap(), -INFINITY);
}

#[test]
fn test_linebreaks() {
assert_eq!(
Expand Down

0 comments on commit 9e38c63

Please sign in to comment.