Login

Significant digits filter

Author:
joelegner
Posted:
March 13, 2009
Language:
Python
Version:
1.0
Tags:
filter filters math engineering
Score:
3 (after 3 ratings)

Formats float values with specified number of significant digits (defaults to 3).

Usage:

{{value|sigdig}} # with 3 significant digits by default {{value|sigdig:digits}}

Examples:

{{0.001432143|sigdig}} renders as 0.00143

{{874321.4327184|sigdig}} renders as 874000

{{874321.4327184|sigdig:5}} renders as 874320

Useful for scientific or engineering presentation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from django import template
import math

register = template.Library()

def sigdig(value, digits = 3):
    order = int(math.floor(math.log10(math.fabs(value))))
    places = digits - order - 1
    if places > 0:
        fmtstr = "%%.%df" % (places)
    else:
        fmtstr = "%.0f"
    return fmtstr % (round(value, places))


register.filter('sigdig', sigdig)

More like this

  1. Converts an integer or floating-point number or a string to a string containing the delimiter character (default comma) after every delimeter_count digits (by default 3 digits) by pikhovkin 3 years, 5 months ago
  2. Smarter USPhoneNumberField by clamothe 7 years ago
  3. Null Field Admin Filter by bcurtu 6 years, 8 months ago
  4. HTML to text filter by MasonM 7 years ago
  5. Javascript Chain Select Widget by ogo 7 years, 2 months ago

Comments

zglennie (on October 18, 2013):

Thanks! Works perfectly. Note - if your input is a string, cast it to float.

#

Please login first before commenting.