Render value to tenths place in nunjucks template?

284 views Asked by At

Using the round() filter I can achieve the correct precision to the tenths place as in

{{ value | round(1) }}

however I still want to display the tenths place if value is zero or a whole integer. (0.0 instead of 0, 3.0 instead of 3)

Is there a different method or other way to render all values to the tenths place?

2

There are 2 answers

0
Don On BEST ANSWER

Here is the logic for the custom filter since the round filter will not maintain a tenths place for zero or whole integers:

nunjucks.configure().addFilter('tenths', function(num) {
        return parseFloat(num).toFixed(1);
    });

Then usage is the same as any filter:

{{ num | tenths }}
2
Aikon Mogwai On

Add you own filter

var env = nunjucks.configure(...

env.addFilter('round1', function(num) {
    if (!isNaN(num))
        return '???';

    return parseFloat(num).toFixed(1);    
});

Usage

{{ value | round1 }}