简体   繁体   中英

How can I use Py3k-style string formatting within Mako templates?

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM