Skip to content

Commit 7c76880

Browse files
support.si_prefix: implement "real" to "scaled with si prefix" number conversion
1 parent f9fbc92 commit 7c76880

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def num_to_si(num, long_prefix=False):
2+
prefixes = [
3+
( 3, 'G', 'Giga' ),
4+
( 2, 'M', 'Mega' ),
5+
( 1, 'k', 'Kilo' ),
6+
( 0, '', '' ),
7+
( -1, 'm', 'mili' ),
8+
( -2, 'u', 'micro' ),
9+
( -3, 'n', 'nano' ),
10+
]
11+
try:
12+
factor, tshort, tlong = next(filter(lambda x: num > (1000 ** x[0]), prefixes))
13+
except StopIteration:
14+
factor, tshort, tlong = prefixes[-1]
15+
prefix = tlong if long_prefix else tshort
16+
return num * (1000 ** -factor), prefix

0 commit comments

Comments
 (0)