python-3.xcheetah

How can you add thousand separator when formatting a number in Cheetah?


I'm trying to format a number as a price in Cheetah3 (Python 3.6). While I have succeeded to limit to 2 decimals using the standard formatting expression, the comma separator doesn't seem to work (I get an error).

Cheetah Expression:

#def format_price($price)
    #if $price < 0.0
        #set $price_str = '($%,.2f)' % (-1.0 * $price)
    #else
        #set $price_str = '$%,.2f' % $price
    #end if
    $price_str
#end def

Error:

ValueError: unsupported format character ',' (0x2c) at ...

Solution

  • It's not a Cheetah problem. That ValueError comes directly from Python:

    $ python3.6
    >>> '($%,.2f)' % -1.0
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: unsupported format character ',' (0x2c) at index 3
    

    You probably want .format().