I need to round a float to be displayed in a UI. e.g, to one significant figure:
JavaScript
x
12
12
1
1234 -> 1000
2
3
0.12 -> 0.1
4
5
0.012 -> 0.01
6
7
0.062 -> 0.06
8
9
6253 -> 6000
10
11
1999 -> 2000
12
Is there a nice way to do this using the Python library, or do I have to write it myself?
Advertisement
Answer
You can use negative numbers to round integers:
JavaScript
1
3
1
>>> round(1234, -3)
2
1000.0
3
Thus if you need only most significant digit:
JavaScript
1
15
15
1
>>> from math import log10, floor
2
>>> def round_to_1(x):
3
return round(x, -int(floor(log10(abs(x)))))
4
5
>>> round_to_1(0.0232)
6
0.02
7
>>> round_to_1(1234243)
8
1000000.0
9
>>> round_to_1(13)
10
10.0
11
>>> round_to_1(4)
12
4.0
13
>>> round_to_1(19)
14
20.0
15
You’ll probably have to take care of turning float to integer if it’s bigger than 1.