Login

roman numbers template filter

Author:
skam
Posted:
April 14, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.