开发者

in python, how do i split a number by the decimal point

So if I run:

a = b / c

and get the result 1.2234开发者_开发技巧

How do i separate it so that I have:

a = 1
b = 0.2234


>>> from math import modf
>>> b,a = modf(1.2234)
>>> print ('a = %f and b = %f'%(a,b))
a = 1.000000 and b = 0.223400
>>> b,a = modf(-1.2234)
>>> print ('a = %f and b = %f'%(a,b))
a = -1.000000 and b = -0.223400


a,b = divmod(a, 1)


Try:

a, b = int(a), a - int(a)

Bonus: works for negative numbers as well. -1.7 is split into -1 and -0.7 instead of -2 and 0.3.

EDIT If a is guaranteed to be non-negative, then gnibbler's solution is the way to go.

EDIT 2 IMHO, Odomontois' solution beats both mine and gnibbler's.


b = a % 1
a = int(a)

or something


You can do it in different ways: 1.With inbuilt function:

def fractional_part(numerator, denominator):
    if denominator != 0:
        return math.modf(numerator/denominator)
    return 0

2.Without inbuilt function:

def fractional_part(numerator, denominator):
    if denominator != 0:
        a = str(numerator/denominator).split(".")[0]
        b = "0." + str(numerator/denominator).split(".")[1]
        return (float(a),float(b))
    return 0


int(a)/b == 1
(a/b)%1 == 0.2234


x = 1.2234

y = str(x/100).split('.')

a = y[0]
b = y[1]

then the result is...

a = 1
b = 2234


You can use also numpy function np.modf:

fractional_part, int_part = np.modf([0,1.2234,3.5])

Of course, this is efficient if you can deal with vectors instead of single numbers one by one.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜