I'm given a decimal_string e.g. 12.34, how would I get the values before and after the decimal point?
a = 12
b = 34
How do I get the values of a
and b
?
I'm given a decimal_string e.g. 12.34, how would I get the values before and after the decimal point?
a = 12
b = 34
How do I get the values of a
and b
?
Edit: After reading comment "This seems to work but if decimal_string is e.g. 0 or 1234 it gives nothing and I need it to be a 0. How would I do this?", I submit the following:
In the following code, we convert the string to a decimal, then:
a
b
. We use the modulus %
operator to get the remainder of division by 1
and then simply strip off
The 0.
from the beginning, converting it back to an int
at the end.Here is the code:
import decimal
try:
num = decimal.Decimal("12.34")
a = int(num)
b = int(str(num % 1)[2:])
except decimal.InvalidOperation:
a = None
b = None
Original: The Python string object has a partition method for this:
a,_,b = "12.34".partition('.')
Note the _
is just a variable that will hold the partition, but isn't really used for anything. It could be anything, like z
.
Another thing to note here is Tuple Unpacking... the partition method returns a tuple with len() of 3. Python will assign the three values to the respective 3 variables on the left.
Alternately, you could do this:
val = "12.34".partition('.')
val[0] # is the left side - 12
val[2] # is the right side - 34
Use split
and join
and then type cast to int
:
s = '12.34'
a = int(''.join(s.split('.')[0])) # 12
b = int(''.join(s.split('.')[1])) # 34
Handling special cases (non-decimal strings):
s = '1234'
if s.find('.') != -1:
a = int(''.join(s.split('.')[0]))
b = int(''.join(s.split('.')[1]))
else:
a = int(s)
b = 0
print(a, b) # 1234 0
Quick and dirty solution without having to go into modulo.
a = int(12.34)
b = int(str(12.34)[3:])
int() will cut off decimal points without rounding. As for the decimal points, turn the number into a string - that lets you manipulate it like an array. Grab the trailing numbers and convert them back to ints.
....
That said, the other answers are way cooler and better so you should go with them