0
def function():
    n=123.456
    x=int(n)
    y=n-int(n)
    print(x,y)

result:

x= 123
y= 0.45600000000000307 

how to get exactly .456 without using library function, n can be any floating number

furas
  • 134,197
  • 12
  • 106
  • 148
ayat ullah sony
  • 1,973
  • 1
  • 10
  • 7
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – metatoaster Nov 04 '19 at 04:36
  • it is natural for float numbers. You can try with standard module `decimal` if you need precise values - `d = decimal.Decimal('123.456')` `print(d - int(d))` – furas Nov 04 '19 at 04:45

4 Answers4

1

If you know from the outset that the number of decimal places is 3, then:

y = round(n - int(n), 3)

If you don't know the number of decimal places, then you can work it out, as so:

y = round(n - int(n), str(n)[::-1].find('.'))

As furas pointed out, you can also use the decimal package:

from decimal import Decimal

n = Decimal('123.456') 
y = n - int(n)
Ian
  • 3,605
  • 4
  • 31
  • 66
1

You can also use the re module:

import re

def get_decimcal(n: float) -> float:
    return float(re.search(r'\.\d+', str(n)).group(0))

def get_decimcal_2(n: float) -> float:
    return float(re.findall(r'\.\d+', str(n))[0])

def get_int(n: float) -> int:
    return int(n)


print(get_decimcal(123.456))
print(get_decimcal_2(123.456))
print(get_int(123.456))

Output

0.456
0.456
123
Emma
  • 27,428
  • 11
  • 44
  • 69
0

Try with round(y,n), and n=3 its the numbers of decimals.

dmigo
  • 2,849
  • 4
  • 41
  • 62
gañañufla
  • 552
  • 2
  • 12
0

You can use %f to round of the floating value to required digits.

def function(n):

    x = int(n)
    y = n-int(n)
    print(x,"%.2f" % y)

function(123.456)

Output:

123

0.456
Ian
  • 3,605
  • 4
  • 31
  • 66