Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python find first non-zero digit after decimal point

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)]
like image 503
Facundo Casco Avatar asked Nov 04 '11 14:11

Facundo Casco


People also ask

How do you get the digits after a decimal in Python?

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 .

How do you find the numbers after a decimal point?

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.

How do you get the digits after the decimal point in a float in Python?

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.

How do you get two values after a decimal in Python?

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.


1 Answers

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)]
like image 94
Sven Marnach Avatar answered Nov 15 '22 17:11

Sven Marnach