1

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?

Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
qwert123
  • 57
  • 2
  • 7
  • 3
    Possible duplicate of [How to get numbers after decimal point?](https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point) – Vivek Kalyanarangan Mar 18 '18 at 04:57

3 Answers3

4

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:

  1. the integer component of it is a
  2. the digits after the integer component are 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
gahooa
  • 131,293
  • 12
  • 98
  • 101
  • 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? – qwert123 Mar 18 '18 at 05:19
2

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
Austin
  • 25,759
  • 4
  • 25
  • 48
-1

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

Farstride
  • 145
  • 11
  • Never mind. Slicing cannot generalise the situation here though, maybe you could get the position of `.` using `string.index` and use slice accordingly. :) – Austin Mar 18 '18 at 05:20