0

Good evening All,

I need help with python project. I am interested in knowing the following.

Let's say I am multiplying 2 numbers together in python.

number = x * y

lets say x is = 3 and y is = 3.2

the total is 9.6

Now I am interested in that .6

I want to assign that .6 to a variable so I can multiply it later on..

how can I assign .6 to a variable?

I tried using the following:

a = 123.4
number_dec = str(a-int(a))[1:]
a2 = number_dec * 2

but it does not work... please help

ParthS007
  • 2,581
  • 1
  • 22
  • 37
NICK
  • 15
  • 6
  • I suggest you check [link](https://stackoverflow.com/questions/5997027/python-rounding-error-with-float-numbers) – MadLordDev Sep 09 '18 at 21:55

3 Answers3

4

Python supports modulo operations on floating point numbers, so you can do this with

>>> 9.6 % 1
0.5999999999999996

Note that this won't give you what you want if the number is negative:

>>> -9.6 % 1
0.40000000000000036

So in general you'll want

frac = abs(value) % 1

This is the fastest of the ones I looked at:

%timeit frac = abs(value) % 1
77.1 ns ± 0.568 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit frac = abs(value) % int(value)
196 ns ± 5.77 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit frac = value - int(value)
156 ns ± 2.42 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
sfjac
  • 7,119
  • 5
  • 45
  • 69
2

given an integer int() truncates the fractional part, so with

n = 4.5
fractional = n - int(n) #0.5

you can get it.

abc
  • 11,579
  • 2
  • 26
  • 51
1

Even easier approach using strings would be :

number = 123.4    
number_dec = str(number).split(".")[1]
print(number_dec)

Output:

4
ParthS007
  • 2,581
  • 1
  • 22
  • 37
  • @PeterWood this won’t give a single character, it will give everything after the `.`, which is just what the OP asked for. (Well, until you try it on a float whose string representation requires exponential notation…) – abarnert Sep 09 '18 at 22:26
  • > Also I assume the example was just for a single decimal place but really they want something more general. I think you missed something. – ParthS007 Sep 09 '18 at 22:29
  • My mistake. Deleted. – Peter Wood Sep 09 '18 at 22:41