I want to take only the first digit after the point of a number that in python 3.7.4

Asked

Viewed 1,240 times

0

I want to take only the number after the dot, type in the number 3.76443 I want to print only the 7, how do I do? how will I also make to print it? I have to create a variable for it?

  • Multiply by 10 and turn to int and then keep the rest of the division by 10.

4 answers

2

At the suggestion of anonymity, multiply by 10 and take the rest of the division by 10 ignoring the decimals. By multiplying 3.76443 by 10 the number turns 37.6443, the rest of the division by 10 is 7.6443. Use % to take the rest of the division and int() to disregard the decimals.

Code:

i=3.76443
print(int(i*10%10))

Upshot:

7

See it working on Ideone: https://ideone.com/c7Z7Up

0

vc can do either mathematically or with type conversion, in this case converting to string and editing

n = 3.76443
ns = str(n)
ponto = ns.find('.')
print(ns[ponto+1])

n1 = n - int(n)
n1 *= 10
n1 = int(n1)
print(n1)
  • wouldn’t have been able to pick up this number using round or % treating it as number?

  • round will round, at example number, it rounds to 3.8, make the split with % will be accurate use the converted number to int, ie more accounts to be done, ñ see pq want to complicate

0

It goes on in the simplest way I could imagine:

 numero = 3.76443
 print(str(numero).split('.')[1][0])

First transforms the variable into a string str(number), then divide it into the point .split('.') as you want, then just take the part after the point [1] and then the first index that exists after the point [0].

0

If you want to import the library math I can do this:

import math

numero = 3.76443
fracao=math.modf(numero)
fracao=str(fracao[0])
print(fracao[2])

In the above case Using you will be using the function modf() which results in a tuple dividing the fraction. In this tuple the "broken" number is in position 0 and the integer in position 1.

Not using the Math (and already bypassing the next number problem to the point being 0), but with a more extensive code:

numero = 3.76443
text = "{:.1f}".format(numero)
if text.endswith(".0"):
    text = text[:-2]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.