将金额转换为2位小数

时间:2016-09-10 15:10:55

标签: nunjucks

我正在使用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?

1 个答案:

答案 0 :(得分:1)

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);