Login

roman numbers template filter

Author:
skam
Posted:
April 14, 2007
Language:
Python
Version:
.96
Tags:
template filter filters roman numbers
Score:
4 (after 4 ratings)

dirt and simple template filter to convert a number to its roman value. taken from dive into python http://www.diveintopython.org/unit_testing/stage_5.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from django.template import Library, TemplateSyntaxError

register = Library()

class RomanError(Exception): pass
class OutOfRangeError(RomanError): pass
class NotIntegerError(RomanError): pass

ROMAN_NUMBER_MAP = (('M',  1000),
                    ('CM', 900),
                    ('D',  500),
                    ('CD', 400),
                    ('C',  100),
                    ('XC', 90),
                    ('L',  50),
                    ('XL', 40),
                    ('X',  10),
                    ('IX', 9),
                    ('V',  5),
                    ('IV', 4),
                    ('I',  1))

def to_roman(n):
    """convert integer to Roman numeral"""
    if not isinstance(n, int):
        try:
            n = int(n)
        except ValueError:
            raise NotIntegerError, "non-integers cannot be converted"
    
    if not (0 < n < 4000):
        raise OutOfRangeError, "number out of range (must be 1..3999)"

    result = ""
    for numeral, integer in ROMAN_NUMBER_MAP:
        while n >= integer:
            result += numeral
            n -= integer
    return result

def roman_number(value):
    """
    Converts a number to its roman value

    Example usage::
        {{ 2007|roman_number }}
        {{ "2007"|roman_number }}
        {{ pub_date|date:"Y"|roman_number }}
    """
    try:
        value = to_roman(value)
    except RomanError, e:
        raise TemplateSyntaxError, "roman_number error: %s" % str(e)
    return value

register.filter('roman_number', roman_number)

More like this

  1. format_thousands by cootetom 4 years, 1 month ago
  2. Truncate filter by zalun 6 years, 3 months ago
  3. Template filter for formatting negative numbers by pkshiu 6 years, 3 months ago
  4. Past days template filter by ramen 5 years, 8 months ago
  5. truncatestring filter by pigletto 6 years, 4 months ago

Comments

Please login first before commenting.