How to get numbers after decimal point?

Viewed 305362

How do I get the numbers after a decimal point?

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

37 Answers

An easy approach for you:

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

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

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

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)

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)

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

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.

import math

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

It definitely worked

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?

You can use this:

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

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))

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

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

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

a = 12.587
b = float('0.' + str(a).split('.')[-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.

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

output: 0.55

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])

If you are using pandas:

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

I've found that really large numbers with really large fractional parts can cause problems when using modulo 1 to get the fraction.

import decimal

>>> d = decimal.Context(decimal.MAX_PREC).create_decimal(
... '143000000000000000000000000000000000000000000000000000000000000000000000000000.1231200000000000000002013210000000'
... )
...
>>> d % 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]

I instead grabbed the integral part and subtracted it first to help simplify the rest of it.

>>> d - d.to_integral()
Decimal('0.1231200000000000000002013210')
def fractional_part(numerator, denominator):
    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

Late in the party, leaving comment for new visitors. If you know you need only 2 decimal places then you can use inbound round

round(1.15 % 1, 2)

I tried a lot of the other solutions but none of them work for me.

In my case, I have different operations and always in the last step, my result has more than the expected decimals.

For example, if you do:

61 * 0.1 the result is the float 6.1000000000000005

To get the 6.1 we have to parse the default float (at least in my case with 64bits) to a lower one:

import numpy as np    

x = 61 * 0.1
y = np.float32(x)

If you have a lot of operations before, try to do the casting at the end :)

To answer better the original questions it would be:

import math
import numpy as np    

x_deci, x_inte = math.modf(5.55)
decimals = np.float32(x_deci)

and the result for the decimals is 0.55 instead of 0.5499999999999998

I was interested in the relative timing of the more sensible answers given here. Using this script on my laptop (MacBookPro16, 6-Core Intel Core i7 2.6 GHz):

#!/bin/sh

python3 -V
python3 -m timeit -s 'a = 5.55' 'b = a % 1'
python3 -m timeit -s 'a = 5.55' 'b = a - a//1'
python3 -m timeit -s 'a = 5.55; import math' 'b = a - math.floor(a)'
python3 -m timeit -s 'a = 5.55' 'b = a - int(a)'
python3 -m timeit -s 'a = 5.55; import math' 'frac, whole = math.modf(a)'

I get the following timing:

Python 3.9.10
10000000 loops, best of 5: 34.9 nsec per loop
5000000 loops,  best of 5: 51   nsec per loop
5000000 loops,  best of 5: 69.2 nsec per loop
5000000 loops,  best of 5: 84.1 nsec per loop
5000000 loops,  best of 5: 97.7 nsec per loop

So the simple % 1 seems the fastest approach

A solution is using modulo and rounding.

import math

num = math.fabs(float(5.55))
rem = num % 1

rnd_by =   len(str(num)) - len(str(int(num))) - 1

print(str(round(rem,rnd_by)))

Your output will be 0.55

Another crazy solution is (without converting in a string):

number = 123.456
temp = 1

while (number*temp)%10 != 0:
    temp = temp *10
    print temp
    print number

temp = temp /10
number = number*temp
number_final = number%temp
print number_final
Related