查找小数位的简单方法 [英] Easy way of finding decimal places

查看:207
本文介绍了查找小数位的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简便的方法或集成函数来找出浮点数的小数位数?

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

该数字是从字符串中解析出来的,所以一种方法是来计算。符号后的数字,但是对我来说这显得很笨拙。是否有可能从 float Decimal 对象中获取所需的信息?

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 :) )

我选择使用python十进制。可以帮助我解决问题的课程:

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

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

注意:仅当构造Decimal的参数是字符串而不是浮点数(导致浮点错误。)

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.

推荐答案

要重复其他人说的内容(因为我已经输入了!),由于小数点之间的差异,我什至不确定这样的值对于浮点数是否有意义和二进制表示;通常,用有限数量的十进制数字表示的数字将只有二进制形式的无限数字表示。

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.

对于 decimal.Decimal 对象,可以使用 as_tuple 方法,该方法返回带有符号位数 c和<$ c的命名元组$ c>指数属性:

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

指数的取反是数字小数点后的位数,除非指数大于 0

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

这篇关于查找小数位的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆