TL; DR
You can do this by calculating the size of the unit part, whether it is negative or not, and then round the number according to the previous numbers.
def num_to_7_char(num):
if num == 0:
return "0.00000"
int_part = int(log10(abs(num))) + 1
minus_part = int(num < 0)
round_to = max(6 - int_part - minus_part, 0)
return "{num:.{round_to}f}".format(num=num, round_to=round_to)
Code working in Repl.it
Explanation
If the number is zero, it returns 0.00000
because a logarithm of 0 can not be calculated.
To calculate the unit part of the number I use the method math.log10
to know how many houses the number has, calculating how many times I have to multiply the number 10
to reach the desired number. Ex.:
from math import log10
print(log10(1)) # 0
print(log10(10)) # 1
print(log10(100)) # 2
I use the abs method to get the module of a number, because to calculate a logarithm the number must be greater than 0.
I use int to convert the result to an integer and sum 1
so that the number of unit digits of the number.
To compute the space that will be occupied by the character -
(minus sign) I make a simple boolean to integer conversion, where True
will become 1
and False
will become 0
.
The variable round_to
stores the amount we want in decimal places, as this will depend on how many characters will be to the left of the point.
The rounding calculation is done by decreasing the whole part and the part of the signal of the desired total. In this case the desired total is 6, as it is necessary to consider that the point will occupy a character.
max is being used so that round_to
is not negative , it sets the minimum threshold to zero. Ex.:
max(1, 0) # 1
max(0, 0) # 0
max(-1, 0) # 0
At the end formatting strings is used using the str.format
to round and limit the number.
The PyFormat site has good examples to understand how it works.
See that this template does not work correctly in some cases for obvious reasons certain numbers are not possible to be represented in 7 characters without specifying some other rules, for example:
- Number greater than
9_999_999
: it would take at least 8 characters to represent them.
- 6-digit integers: The algorithm uses the rule to convert a
int
to float
and fill in the remaining characters with zeros on the right, but if an integer has only 6 digits it can not be represented as just add one point, without being able to add zeros.