>> 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
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
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)
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
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
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'
#!/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)'
我得到了以下时间:
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