meteor, mongodb, spacebars, how do I display only 2 decimal places

感情迁移 提交于 2020-01-04 08:09:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!