求小数点后的位数 [英] Find the number of digits after the decimal point

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

问题描述

我正在尝试编写 Python 2.5.4 代码来编写一个函数,该函数将浮点数 x 作为输入并返回 x 中小数点后的位数.

I'm trying to write a Python 2.5.4 code to write a function that takes a floating-point number x as input and returns the number of digits after the decimal point in x.

这是我的代码:

def number_of_digits_post_decimal(x):
    count = 0
    residue = x -int(x)
    if residue != 0:
        multiplier = 1
        while int(multiplier * residue) != (multiplier * residue):
            count += 1
            multiplier = 10 * multiplier
            print count
            print multiplier
            print multiplier * residue
            print int(multiplier * residue)
            return count

print number_of_digits_post_decimal(3.14159)

while 循环中的打印语句仅用于调试目的.

The print statements within the while loop are only for debugging purposes.

现在当我运行这段代码时,我得到以下输出.

Now when I run this code, I get the following as output.

1

10

1.4159

1

2

100

14.159

14

3

1000

141.59

141

4

10000

1415.9

1415

5

100000

14159.0

14158

6

1000000

141590.0

141589

7

10000000

1415900.0

1415899

8

100000000

14159000.0

14158999

9

1000000000

....

此函数返回的 count 最终值为 17.

The final value of count as returned by this function is 17.

如何修改这段代码才能达到我们想要的效果?

How to modify this code in order to achieve our desired result?

推荐答案

这是您可能喜欢的快捷方式:

Here's a shortcut that you might like:

def num_after_point(x):
    s = str(x)
    if not '.' in s:
        return 0
    return len(s) - s.index('.') - 1

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

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