Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - Easy way of finding decimal places

Is there an easy way or integrated function to find out the decimal places of a floating point number?

The number is parsed from a string, so one way is to count the digits after the '.' sign, but that looks quite clumsy to me. Is there a possibility to get the information needed out of a float or Decimal object?

SOLUTION (one of them, of course :) )

I chose to use the python decimal.Decimal class to help me with my problem:

e = abs(Decimal(string_value).as_tuple().exponent)

NOTE: this only works when the parameter from which the Decimal is constructed is a string and not a float (which would lead to floating point inaccuracies).

Thanks a lot for all other contributions.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To repeat what others have said (because I had already typed it out!), I'm not even sure such a value would be meaningful in the case of a floating point number, because of the difference between the decimal and binary representation; often a number representable by a finite number of decimal digits will have only an infinite-digit representation in binary.

In the case of a decimal.Decimal object, you can retrieve the exponent using the as_tuple method, which returns a namedtuple with sign, digits, and exponent attributes:

>>> d = decimal.Decimal('56.4325')
>>> d.as_tuple().exponent
-4
>>> d = decimal.Decimal('56.43256436')
>>> d.as_tuple().exponent
-8

The negation of the exponent is the number of digits after the decimal point, unless the exponent is greater than 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...