tags:

views:

119

answers:

7

how do i get the numbers after a decimal point?

for example if i have 5.55

how do i get .55?

+1  A: 

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)
Jim Brissom
+4  A: 
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.

jer
Note also that this probably doesn't do what you want for negative numbers: `-5.55%1 = 0.45` on my machine. `math.modf()` does the right thing.
ire_and_curses
A: 

Try Modulo:

5.55%1 = 0.54999999999999982
Juri Robl
A: 
import math
orig = 5.55
whole = math.floor(orig)    # whole = 5.0
frac = orig - whole         # frac = 0.55
lacqui
A: 

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
thyrgle
If you're going to `import math`, why not just use `math.modf()`?
ire_and_curses
@ire_and_curses: I am providing an alternative solution to the problem.
thyrgle
+3  A: 

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.

intuited
For the benefit of the original question-asker: floats must be converted to a strings before they can be converted to Decimals. So if you have `n = 5.55`, n is a float, and you should do `Decimal(str(n)) % 1` to get the fractional part. (This isn't necessary if you have an integer, but it doesn't hurt.)
kindall
@kindall: Aye, good point.
intuited
A: 
>>> n=5.55
>>> if "." in str(n):
...     print "."+str(n).split(".")[-1]
...
.55
ghostdog74
This is OK for garden-variety numbers, but doesn't work so well for numbers large (or small) enough to require scientific notation.
kindall