简体   繁体   English

meteor,mongodb,spacebars,我如何只显示2位小数

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

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%. 我有一个像{ "pctFail" : "0.3515500159795462" }这样的值的集合,当我将其传递给模板并显示为{{myTemplate}}%时,它在我的html中显示为0.3515500159795462%。 How do I display this as 0.35% ? 我如何将其显示为0.35%?

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. 然后像以前一样使用{{pctFail}}% If you insist on storing the numerical property as a string, you'll need to return something like parseFloat(this.pctFail).toFixed(2) instead. 如果您坚持将数字属性存储为字符串,则需要返回类似parseFloat(this.pctFail).toFixed(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: 您也可以使用辅助函数http://docs.meteor.com/#/full/template_registerhelper解决此问题,该函数可以在所有模板中使用,如下所示:

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. 代替。

You could do something like this using substrings 你可以使用子串做这样的事情

Template,myTemplate.helpers({
    pctFail: function () {
        return this.pctFail.substring(0, 4);
    }
)};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用流星空格键显示文档ID? - How Do I Display Document ID Using Meteor Spacebars? Meteor JS:如何使用Spacebars显示从Meteor Collection中检索到的数组内的内容 - Meteor JS: How to use Spacebars to display contents inside an array retrieved from Meteor Collection meteor.js&mongodb-如何在空格键中传递当前元素的_id - meteor.js & mongodb - how to pass _id of current element in spacebars each 如何在使用meteor.js时从Mongodb获取数据以在Fullcalendar中显示 - How do I get data from Mongodb to display in Fullcalendar while using meteor.js 如何在 MongoDB 中的 findOne 之后仅显示数组的一部分? - How do I display only part of the array after findOne in MongoDB? 在mongodb中四舍五入到小数点后两位 - Rounding to 2 decimal places in mongodb 我如何使用流星搜索集合,并且仅显示匹配结果? - How do I live search a collection using meteor, and ONLY display matching results? 如何连接到Meteor应用程序中的外部MongoDB集合 - How do I connect to an external MongoDB Collection in a Meteor App 如何使用meteor将对象数组插入mongodb? - how do I insert an array of objects to mongodb using meteor? 如何使用动态变量作为Meteor / MongoDB集合名称? - How do I use a dynamic variable as a Meteor/MongoDB collection name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM