Simple problem, how to find the first non-zero digit after decimal point. What I really need is the distance between the decimal point and the first non-zero digit.
I know I could do it with a few lines but I'd like to have some pythonic, nice and clean way to solve this.
So far I have this
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
How do you get the number after the decimal point in Python? modf() to get the digits after the decimal point. Call math. modf(x) to return a tuple with the fraction and integer parts of x .
The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left.
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.
The easiest way seems to be
x = 123.0
dist = int(math.log10(abs(x)))
I interpreted the second entry in each pair of the list t
as your desired result, so I chose int()
to round the logarithm towards zero:
>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With