is there a filter to fix floating point precision?

225 views
Skip to first unread message

Jacob G

unread,
Oct 27, 2015, 8:56:10 AM10/27/15
to Nunjucks
I'd like to fix floating point precision (using rounding if necessary), as in:
  • 3 => "3.00"
  • 2.4 => "2.40"
  • 2.45 => "2.45"
  • 2.455 => "2.46"
  • 2.454 => "2.45"
The rounding filter does not fix precision, rather it's a max precision, i.e.,:
  • 2.4 | round(2) => 2.4
Is there such a filter in nunjucks? In jinja, the format filter could be used for that, but that filter uses native python formatting.

Jacob G

unread,
Oct 27, 2015, 9:16:42 AM10/27/15
to Nunjucks
This'll do it:

installFixed: function () {

function fixedFilter (number, digits) {

return number.toFixed(digits);
}

this.getEnv().addFilter('fixed', fixedFilter);
},

hafi...@gmail.com

unread,
Jan 24, 2018, 6:40:48 AM1/24/18
to Nunjucks
Try this directly, without any custom filters:

{{ ( numberToDisplay|float ).toFixed(2)}}
Reply all
Reply to author
Forward
0 new messages