2

I have the following code and result and I would need each number to be rounded to the first decimal but the lowest one ex: 7.166666666666667 to be 7.1 and not 7.2

I have tried with round_down but it still rounds up

for x in range(0, 9):
    income_visits=(income_euro[x]/visits[x])
    print(income_visits)

7.166666666666667
7.0
7.666666666666667
11.0
0.1111111111111111
11.333333333333334
162.0
55.0
9.0
David Buck
  • 3,594
  • 33
  • 29
  • 34
Vir
  • 33
  • 5

3 Answers3

0

here's a little function that does it for you:

def round_down(n, decimals=0):
    multiplier = 10 ** decimals
    return math.floor(n * multiplier) / multiplier

make sure to import the math library.

example usage:

print(round_down(1.7777, 1))
print(round_down(1.7777, 2))
print(round_down(1.7777, 3))

output:

1.7
1.77
1.777
Gal
  • 494
  • 4
  • 11
0

Here is the solution. Try this..

number = YOUR_NUMBER

float(str(int(number)) + '.' + str(number-int(number))[2:3])

>>> number = 7.166666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>> 
>>> number = 7.116666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>> 
>>> number = 7.196666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )
7.1
>>>
>>> number = 7.096666666666667
>>> print( float(str(int(number)) + '.' + str(number-int(number))[2:3]) )

Ashish Sondagar
  • 591
  • 1
  • 4
  • 10
0

This could also work.

num = 7.166666666667
print(int(num*10)/10)

What this does is it takes the number (i.e. 7.1666...) multiplies it by 10(71.666...) that way when an integer is taken from it, it returns a whole number (71), then it divides again to get just one decimal place (7.1). Hope this helps.

Humayun Ahmad Rajib
  • 1,488
  • 1
  • 9
  • 20
Dave N
  • 1
  • 1
  • 4