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

3

2

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% ?

Humanize answered 20/12, 2014 at 7:2 Comment(0)
T
7

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.

Templeton answered 20/12, 2014 at 7:16 Comment(3)
Thanks Donny, I have several items in my collection that I want to apply this .toFixed(2) function to. My current helper just returns them all in a return Items.find() sort of fashion and then I iterate over all of them with a block helper {{#each items}} sort of fashion. Is there a way I can apply to all of the return values which are double values? like return Wafers.find().toFixed(2) or do I have to create a helper for each one of my keys which are of this 'pct' type?Humanize
Ok, I just made a method for each of my items (i.e. 'pctFail', 'pctX', 'pctY', etc.) just being generic here but I had 7 data items that were in pct which I needed to convert to a 2 decimal fixed precision. I wanted something general which would handle everything, but creating 7 helper methods wasn't bad. Thanks again Donny!Humanize
could you please share your code? I have the same issue, but I do not get it how to apply this answer to Items.find()Siderite
J
1

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.

Josejosee answered 29/1, 2016 at 21:55 Comment(0)
H
0

You could do something like this using substrings

Template,myTemplate.helpers({
    pctFail: function () {
        return this.pctFail.substring(0, 4);
    }
)};
Haymo answered 15/4, 2015 at 18:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.