Reputation: 4343
I'm working on a Pyramid project using Mako templates, and I'm trying to display some floating-point numbers. The numbers are expressed as floats in my code, but I'd like to truncate them to 2 decimal places for display to users. It's well-established that round()
is not a good way to truncate floating-point numbers. Since I only want to truncate them for display, I'm inclined to just use string-formatting instead of going to the length of using the Decimal
module.
I found an older question here that shows how to use Python 2.x string formatting within a Mako template - but how can I use Python 3.x string formatting instead?
>>>> "We display two significant digits: {0:.2f}".format(34.567645765)
'We display two significant digits: 34.57'
This is probably in the documentation and/or discoverable by experimentation, but I'd also like to replace the old answer with one that works for Python 3.x.
Upvotes: 3
Views: 1550
Reputation: 154464
Exactly the same way:
>>> from mako.template import Template
>>> Template("We display two significant digits: ${'{0:.2f}'.format(34.567645765)}").render()
'We display two significant digits: 34.57'
Upvotes: 10