The Python Oracle

How to get numbers after decimal point?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping

--

Chapters
00:00 Question
00:21 Accepted answer (Score 30)
00:34 Answer 2 (Score 273)
00:57 Answer 3 (Score 197)
01:10 Answer 4 (Score 81)
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/3886...

Answer 2 links:
[modf]: https://docs.python.org/2/library/math.h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #floatingpoint #decimal

#avk47



ANSWER 1

Score 283


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.




ANSWER 2

Score 85


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)



ANSWER 3

Score 44


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.




ACCEPTED ANSWER

Score 31


An easy approach for you:

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