Currently I have the scenario where I need to display calculation in nunjucks.
{{ cdItem.price * cdItem.addedquantity}}
Suppose the price is 296.10 and quantity is 3, Nunjucks prints this out as 888.3000000000001
Surprisingly it shows correctly for quantity 2 and 4.
Please suggest me a way so that I can prevent this calculate till 2 digits after decimal.
like this 888.30
This question is more appropriate for stack overflow. But since you're here, you have a few options:
Number.prototype.toFixed() in your template:var result = nunjucks.renderString('{{ (a * b).toFixed(2) }}', {a: 296.10, b: 3});
{{ val|toFixed(digits) }} where val might be a string representation of a float, for instance, or if you wanted to do something more involved like localization of currency:var env = new nunjucks.Environment();
env.addFilter('toFixed', function(num, digits) {
return parseFloat(num).toFixed(digits)
});
var result = env.renderString('{{ (a * b)|toFixed(2) }}', {a: 296.10, b: 3});
// or
var result = env.renderString('{{ a|toFixed(2) }}', {a: '888.3'});
// this also works, without the need for a custom filter
var result = nunjucks.renderString('{{ (a|float).toFixed(2) }}', {a: '888.3'});
In all cases above, result will equal '888.30'
Hey @fdintino , Thank you very much for quick reply but I have to do this in nunjucks file itself. I tried your solution {{ (cdItem.price * cdItem.addedquantity).toFixed(2) }}
And it gives me error.
Is there anything that I can directly use in nunjucks file?
This was from quite some time ago, but I believe @fdintino solution is overkill. You could just as well use {{ myNum | round(2) }}
Most helpful comment
This question is more appropriate for stack overflow. But since you're here, you have a few options:
Number.prototype.toFixed()in your template:{{ val|toFixed(digits) }}wherevalmight be a string representation of a float, for instance, or if you wanted to do something more involved like localization of currency:In all cases above,
resultwill equal'888.30'