开发者

Are there any methods that returns just the decimal after a division? (Python3)

In python 3, are there any methods that would return just the decimal value after a division?

For example, if I divided 4 by 5 in this method, it w开发者_Go百科ould return 8.


Use floating-point division. e.g.:

(11.0 / 5) % 1 = 0.20000000000000018

(1.0 * 11 / 5) % 1 = 0.20000000000000018


How about this?

>>> int(((4.0 / 5.0) % 1) * 10)
8


You can easily calculate it using int, for a generic number a:

int(10*a)%10

However, note that this only works for positive numbers!

If you want it to work for negative numbers as well:

int(10*a*cmp(a,0))%10*cmp(a,0)


You can do this without floating point operations, right?

foo=lambda x,y: (10*(x%y))/y)

# Demo
>>> for i in range(20):
...   print(foo(i,7), i/7.0)
... 
(0, 0.0)
(1, 0.14285714285714285)
(2, 0.2857142857142857)
(4, 0.42857142857142855)
(5, 0.5714285714285714)
(7, 0.7142857142857143)
(8, 0.8571428571428571)
(0, 1.0)
(1, 1.1428571428571428)
(2, 1.2857142857142858)
(4, 1.4285714285714286)
(5, 1.5714285714285714)
(7, 1.7142857142857142)
(8, 1.8571428571428572)
(0, 2.0)
(1, 2.1428571428571428)
(2, 2.2857142857142856)
(4, 2.4285714285714284)
(5, 2.5714285714285716)
(7, 2.7142857142857144)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜