Advertisements
i want convert the float to [0.something] but my data have very different numbers like
123.456,
12.3456,
1234.56
i know i can do
ConvertNum = 123.456
convertNum /= 1000
print(convertNum)
but my problem is if when i don’t know how many 10 multiplication i need to make it 0.something
so i tried something like this
ConvertNum = 123.456
convertStr = str(ConvertNum).split(".")
convertStr = f"0.{convertStr[0] + convertStr[1]}"
print(float(convertStr))
but my question is, is this the best way to do that?
is there any function like in math library that can do it automatically?
>Solution :
Use maths… The number of whole digits in a number can be found using log
:
from math import ceil, log10
def normalize(a):
return a / 10 ** ceil(log10(a))
Test cases:
>>> print(normalize(1.23))
0.123
>>> print(normalize(123.45))
0.12345
>>> print(normalize(0.1))
0.1