Search code examples
nunjucks

Convert the amount to 2 decimals


I am using nunjucks template:

<td class="alignright">{{ item.amount / 100 }}</td>

Using 10050 / 100, I am getting 100.5, I want to have it like 100.50.

Question:

How do I convert the amount to 2 decimals, after divided by 100?

Solution

  • env = nunjucks.configure( ... );
    ...
    env.addFilter('fixed', function(num, length) {
        return num.toFixed(length || 2);
    });
    

    <td class="alignright">{{ item.amount / 100 | fixed }}</td> <= need parenthesis!
    

    Worked example

    var nunjucks  = require('nunjucks');
    var env = nunjucks.configure();
    
    env.addFilter('fixed', function(num, length) {
        return  num.toFixed(2 || length);
    });
    
    env.addGlobal('fixed', function(num, length) { 
        return  num.toFixed(2 || length);
    })
    
    var html = env.renderString(
        'Filter: {{ (totalAmt / 100) | fixed }}, GlobalFunc: {{ fixed(totalAmt / 100) }}', 
        { totalAmt: 500030 });
    console.log(html);