2

我正在使用nunjucks模板:

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

使用10050 / 100,我得到100.5,我想拥有它100.50

问题:

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

1 回答 1

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

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

工作示例

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);
于 2016-09-10T19:10:32.350 回答