How do I truncate floats to two decimal places in cheetah templates?

575 views Asked by At

I'm currently using Cheetah Templates with my python code and I'm passing in a number of floating point numbers. I'd like to truncate these floats to only two decimal places within the template, e.g. 0.2153406 would become 0.21

Is it possible to do this within the Cheetah template of do I have to pass in already truncated strings?

3

There are 3 answers

0
Ricky On

To run examples use print("FORMAT".format(NUMBER)); So to get the output of the first example, you would run: print("{:.2f}".format(3.1415926));

Will Output

3.14    2 decimal places 
0
Andrew Thompson On

I just discovered a solution via output from complex expressions using #echo:

  • #echo '%.2f' % $my_float_var#

This prints out my float in the variable $my_float_var with only two decimal places.

0
Jim On

#echo works, but you can instead define your own filter class to take control of formatting details, letting you write simpler templates. Here's a filter that rounds floats to a certain precision.

import Cheetah.Filters

class MyFilter(Cheetah.Filters.Filter):
    """
    Overrides filtering to control the number of digits output for
    floats.
    """
    def filter(self,val,numDigits=2,**kw):
        """
        Called each time a top level placeholder is to be
        formatted for output.
        """
        if isinstance(val,float):
            return f"{val:.{numDigits}f}"

        return super().filter(val,**kw)

To use this custom filter, specify it when you create your template. Here's one way.

cls=Cheetah.Template.Template.compile(tmpl)
print(cls(filter=MyFilter))

You can also add custom arguments to your filter function, like numDigits in the above example. To specify that value, you have to use the long form in placeholders.

#import math

π to two digits is $math.pi
π to ten digits is ${math.pi,numDigits=10}

This is an old question, but earlier answers don't mention filters, even though formatting placeholders is their primary purpose.

Jim