I am trying to implement a simple function of float numbers and I got this error: Unknown format code 'g' for object of type 'str. What is the cause of this and how do I resolve this.
from django import template
register = template.Library()
@register.filter
def human_format(num):
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
You're passing in a string, not a number, and trying to use number formatting codes on it.
However, are you maybe looking for the built-in filesizeformat
?
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.