0
   present_values = random.sample(xrange(1,1000),5)
   print present_values
   present_values1 = [(x / 9) * 5 for x in present_values]
   print (present_values1)
   present_values2 = [(x / 9) * 4 for x in present_values]
   print present_values2

How to get the values of present_values1 and present_values2 variables as decimal numbers while i am getting integers right now?

1 Answers1

0

In 2.7, dividing an integer by an integer will result in an integer. For example,

>>> 35 / 9
3

In order for arithmetic to not result in an integer, at least one of its operands must be a non-integer.

Convert present_values into a list of Decimals before doing arithmetic on it.

import random
from decimal import Decimal

present_values = random.sample(xrange(1,1000),5)

#choose one:
present_values = map(Decimal, present_values) 
#or 
present_values = [Decimal(x) for x in present_values]

print present_values
present_values1 = [(x / 9) * 5 for x in present_values]
print (present_values1)
present_values2 = [(x / 9) * 4 for x in present_values]
print present_values2

Now your results will be Decimals. Example output:

[Decimal('209'), Decimal('15'), Decimal('372'), Decimal('367'), Decimal('516')]
[Decimal('116.1111111111111111111111111'), Decimal('8.333333333333333333333333335'), Decimal('206.6666666666666666666666666'), Decimal('203.88888888888888888888
88889'), Decimal('286.6666666666666666666666666')]
[Decimal('92.88888888888888888888888888'), Decimal('6.666666666666666666666666668'), Decimal('165.3333333333333333333333333'), Decimal('163.11111111111111111111
11111'), Decimal('229.3333333333333333333333333')]

If you don't literally mean "the Decimal data type, found in the decimal module" and instead generally mean "any numerical data type that can represent numbers that have a decimal point", then you can do the same thing with floats.

present_values = [float(x) for x in present_values]

Alternative approach: in 3.X, dividing an integer by an integer may result in a non-integer. You can backport this behavior to 2.7 by doing:

from __future__ import division

Then the rest of your code should produce "decimal" output without any additional changes.

Kevin
  • 74,910
  • 12
  • 133
  • 166