Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python convert 123.456 to 0.123456

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading