Hướng dẫn python get decimal part

How do I get the numbers after a decimal point?

Show

For example, if I have 5.55, how do i get .55?

Hướng dẫn python get decimal part

jpp

152k32 gold badges256 silver badges319 bronze badges

asked Oct 7, 2010 at 22:38

Alex GordonAlex Gordon

55k281 gold badges656 silver badges1037 bronze badges

3

5.55 % 1

Keep in mind this won't help you with floating point rounding problems. I.e., you may get:

0.550000000001

Or otherwise a little off the 0.55 you are expecting.

answered Oct 7, 2010 at 22:40

9

Use modf:

>>> import math
>>> frac, whole = math.modf(2.5)
>>> frac
0.5
>>> whole
2.0

answered May 16, 2014 at 18:58

Hướng dẫn python get decimal part

Anthony VAnthony V

2,0901 gold badge10 silver badges6 bronze badges

4

What about:

a = 1.3927278749291
b = a - int(a)

b
>> 0.39272787492910011

Or, using numpy:

import numpy
a = 1.3927278749291
b = a - numpy.fix(a)

answered Oct 7, 2010 at 22:40

Jim BrissomJim Brissom

30.6k3 gold badges37 silver badges33 bronze badges

0

Using the decimal module from the standard library, you can retain the original precision and avoid floating point rounding issues:

>>> from decimal import Decimal
>>> Decimal('4.20') % 1
Decimal('0.20')

As kindall notes in the comments, you'll have to convert native floats to strings first.

answered Oct 7, 2010 at 22:46

intuitedintuited

22.3k7 gold badges63 silver badges87 bronze badges

5

An easy approach for you:

number_dec = str(number-int(number))[1:]

answered Mar 5, 2012 at 5:02

lllluuukkelllluuukke

1,2942 gold badges12 silver badges17 bronze badges

14

Try Modulo:

5.55%1 = 0.54999999999999982

answered Oct 7, 2010 at 22:40

Juri RoblJuri Robl

5,4542 gold badges30 silver badges44 bronze badges

To make it work with both positive and negative numbers: try abs(x)%1. For negative numbers, without with abs, it will go wrong.

5.55 % 1

output 0.5499999999999998

-5.55 % 1

output 0.4500000000000002

answered Mar 12, 2021 at 18:19

Hướng dẫn python get decimal part

import math
orig = 5.55
whole = math.floor(orig)    # whole = 5.0
frac = orig - whole         # frac = 0.55

answered Oct 7, 2010 at 22:42

Kevin LacquementKevin Lacquement

5,0213 gold badges24 silver badges30 bronze badges

1

similar to the accepted answer, even easier approach using strings would be

def number_after_decimal(number1):
    number = str(number1)
    if 'e-' in number: # scientific notation
        number_dec = format(float(number), '.%df'%(len(number.split(".")[1].split("e-")[0])+int(number.split('e-')[1])))
    elif "." in number: # quick check if it is decimal
        number_dec = number.split(".")[1]
    return number_dec

answered Jan 26, 2018 at 14:55

yosemite_kyosemite_k

2,9541 gold badge15 silver badges26 bronze badges

3

>>> n=5.55
>>> if "." in str(n):
...     print "."+str(n).split(".")[-1]
...
.55

answered Oct 7, 2010 at 23:42

ghostdog74ghostdog74

314k55 gold badges252 silver badges339 bronze badges

1

Just using simple operator division '/' and floor division '//' you can easily get the fraction part of any given float.

number = 5.55

result = (number/1) - (number//1)

print(result)

answered Apr 10, 2020 at 1:38

SonySony

551 silver badge5 bronze badges

Sometimes trailing zeros matter

In [4]: def split_float(x):
   ...:     '''split float into parts before and after the decimal'''
   ...:     before, after = str(x).split('.')
   ...:     return int(before), (int(after)*10 if len(after)==1 else int(after))
   ...: 
   ...: 

In [5]: split_float(105.10)
Out[5]: (105, 10)

In [6]: split_float(105.01)
Out[6]: (105, 1)

In [7]: split_float(105.12)
Out[7]: (105, 12)

answered Jul 20, 2018 at 0:20

Hướng dẫn python get decimal part

George FisherGeorge Fisher

2,8162 gold badges15 silver badges15 bronze badges

1

Another example using modf

from math import modf
number = 1.0124584

# [0] decimal, [1] integer
result = modf(number)
print(result[0])
# output = 0124584
print(result[1])
# output = 1

answered Mar 24, 2020 at 16:01

This is a solution I tried:

num = 45.7234
(whole, frac) = (int(num), int(str(num)[(len(str(int(num)))+1):]))

answered Jan 4, 2015 at 17:00

kuriankurian

1712 silver badges10 bronze badges

Float numbers are not stored in decimal (base10) format. Have a read through the python documentation on this to satisfy yourself why. Therefore, to get a base10 representation from a float is not advisable.

Now there are tools which allow storage of numeric data in decimal format. Below is an example using the Decimal library.

from decimal import *

x = Decimal('0.341343214124443151466')
str(x)[-2:] == '66'  # True

y = 0.341343214124443151466
str(y)[-2:] == '66'  # False

answered Feb 11, 2018 at 12:49

Hướng dẫn python get decimal part

jppjpp

152k32 gold badges256 silver badges319 bronze badges

Use floor and subtract the result from the original number:

>> import math #gives you floor.
>> t = 5.55 #Give a variable 5.55
>> x = math.floor(t) #floor returns t rounded down to 5..
>> z = t - x #z = 5.55 - 5 = 0.55

answered Oct 7, 2010 at 22:42

4

Example:

import math
x = 5.55
print((math.floor(x*100)%100))

This is will give you two numbers after the decimal point, 55 from that example. If you need one number you reduce by 10 the above calculations or increase depending on how many numbers you want after the decimal.

Hướng dẫn python get decimal part

ilim

4,3827 gold badges27 silver badges44 bronze badges

answered Sep 30, 2017 at 7:03

Hướng dẫn python get decimal part

FrankFrank

193 bronze badges

2

import math

x = 1245342664.6
print( (math.floor(x*1000)%1000) //100 )

It definitely worked

Blaztix

1,1651 gold badge18 silver badges28 bronze badges

answered Feb 24, 2019 at 0:13

1

Another option would be to use the re module with re.findall or re.search:

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(5.55))
print(get_decimcal_2(5.55))
print(get_int(5.55))

Output

0.55
0.55
5

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Source

How to get rid of additional floating numbers in python subtraction?

answered Nov 4, 2019 at 5:16

Hướng dẫn python get decimal part

EmmaEmma

26.9k10 gold badges41 silver badges65 bronze badges

You can use this:

number = 5.55
int(str(number).split('.')[1])

answered Jul 24, 2020 at 3:43

2

This is only if you want toget the first decimal

print(int(float(input()) * 10) % 10)

Or you can try this

num = float(input())
b = num - int(num) 
c = b * 10
print(int(c))

answered Sep 23, 2020 at 7:16

Using math module

speed of this has to be tested

from math import floor

def get_decimal(number):
    '''returns number - floor of number'''
    return number-floor(number)

Example:

n = 765.126357123

get_decimal(n)

0.12635712300004798

answered Nov 10, 2020 at 7:05

Hướng dẫn python get decimal part

1

def fractional_part(numerator, denominator):
    # Operate with numerator and denominator to 
# keep just the fractional part of the quotient
if  denominator == 0:
      return 0
  else:
       return (numerator/ denominator)-(numerator // denominator)  
 

print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0

answered Nov 13, 2020 at 15:11

Easier if the input is a string, we can use split()

decimal = input("Input decimal number: ") #123.456

# split 123.456 by dot = ['123', '456']
after_coma = decimal.split('.')[1] 

# because only index 1 is taken then '456'
print(after_coma) # '456'

if you want to make a number type print(int(after_coma)) # 456

answered Nov 24, 2020 at 4:21

Hướng dẫn python get decimal part

a = 12.587
b = float('0.' + str(a).split('.')[-1])

Hướng dẫn python get decimal part

S.B

9,2087 gold badges19 silver badges40 bronze badges

answered Jun 9 at 22:48

EwinEwin

112 bronze badges

1

What about:

a = 1.234
b = a - int(a)
length = len(str(a))

round(b, length-2)

Output:
print(b)
0.23399999999999999
round(b, length-2)
0.234

Since the round is sent to a the length of the string of decimals ('0.234'), we can just minus 2 to not count the '0.', and figure out the desired number of decimal points. This should work most times, unless you have lots of decimal places and the rounding error when calculating b interferes with the second parameter of round.

answered Apr 23, 2017 at 14:58

M HM H

933 silver badges6 bronze badges

1

You may want to try this:

your_num = 5.55
n = len(str(int(your_num)))
float('0' + str(your_num)[n:])

It will return 0.55.

answered Jun 22, 2019 at 0:50

Hướng dẫn python get decimal part

number=5.55
decimal=(number-int(number))
decimal_1=round(decimal,2)
print(decimal)
print(decimal_1)

output: 0.55

answered Jul 12, 2019 at 18:32

Sanchit AlunaSanchit Aluna

4152 gold badges6 silver badges20 bronze badges

See what I often do to obtain numbers after the decimal point in python 3:

a=1.22
dec=str(a).split('.')
dec= int(dec[1])

Hướng dẫn python get decimal part

Suraj Rao

29.1k11 gold badges95 silver badges101 bronze badges

answered Oct 8, 2019 at 7:15

If you are using pandas:

df['decimals'] = df['original_number'].mod(1)

answered Oct 23, 2019 at 19:58

Hướng dẫn python get decimal part

erickfiserickfis

91411 silver badges19 bronze badges