问题
I have a collection that has values like { "pctFail" : "0.3515500159795462" }
and when I pass this to a template and display as {{myTemplate}}% it displays in my html as 0.3515500159795462%. How do I display this as 0.35% ?
回答1:
You could override the data context's property with a template helper method:
Template.myTemplate.helpers({
pctFail: function () { return this.pctFail.toFixed(2); }
})
And then use {{pctFail}}%
as before. If you insist on storing the numerical property as a string, you'll need to return something like parseFloat(this.pctFail).toFixed(2)
instead.
回答2:
You can also solve this problem by using a helper function http://docs.meteor.com/#/full/template_registerhelper which can be used from all templates like so:
Template.registerHelper('toFixed', function (x, decimals) {
return x.toFixed(decimals);
})
and then you can use:
{{toFixed item.pctFail 2}}
If you insist on storing the numerical property as a string, you'll need to return something like
parseFloat(x).toFixed(decimals)
instead.
回答3:
You could do something like this using substrings
Template,myTemplate.helpers({
pctFail: function () {
return this.pctFail.substring(0, 4);
}
)};
来源:https://stackoverflow.com/questions/27577891/meteor-mongodb-spacebars-how-do-i-display-only-2-decimal-places