1

After looking at the various math, float, and decimal functions in Python, I haven't found what I'm looking for. In my program, there may be instances when it will return a float and I need the float information so that I can do another function. Let's say based on the user's input the quotient we're working with is 1.4, which I will represent as X.Y. How do I isolate Y so that I can use a FOR statement. (I need the program to do something 4 times in this case.) I've tried playing with the % function, but that returns the remainder, not the value I'm looking for. I've tried math.fmod and math.modf. Again not what I'm looking for. I looked at this example too.

Community
  • 1
  • 1
Steve Edwards
  • 113
  • 1
  • 5
  • 14

4 Answers4

7

Looks like int((x*10) % 10) will do it:

>>> x = 1.4
>>> int((x*10) % 10)
4
Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
  • Assuming `x` is always an exact tenth---i.e., a number of the form `n / 10.0` for some integer `n`, it would be somewhat safer to do `int(round(x * 10) % 10)`. Otherwise you risk getting the wrong answer when `x * 10` is just a smidgen too small as a result of floating-point inaccuracies. [As it happens, it turns out that with IEEE 754 arithmetic and round-half-to-even, `(n / 10.0) * 10.0 == n` for any exactly representable integer `n`, but that's something of an accident. It doesn't remain true if you replace `10.0` with `100.0`, for example.] – Mark Dickinson Aug 06 '12 at 20:14
  • "any exactly representable integer n". Bah. That should say "Any *sufficiently small* exactly representable integer n." :-) – Mark Dickinson Aug 06 '12 at 20:26
  • ... which is to say, any `n` not larger than `5 * 2**50`. Okay, I'll shut up now. – Mark Dickinson Aug 06 '12 at 20:36
2

How about

x = 1.4
y = 10 * (x - int(x))
>>> 4
Zaur Nasibov
  • 22,280
  • 12
  • 56
  • 83
2

or you could do it as string manipulation

x=1.4
whole,fractional = map(int,str(x).split("."))

afterwards whole is equal to 1 and fractional is equal to 4... and it should work equally well with negative numbers

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Using the following method you can get any position in a float. That is, tenths, hundredths, thousandths and so on:

import math

def get_pos_float(num, unit):
    if unit >= 10:
        num = abs(math.modf(num)[0]) # Get just the fractional part
        num *= 10 # Move the decimal point one place to the right
        return get_pos_float(num, unit/10)
    return int(math.modf(num)[1]) #Return the whole number part

decimalNumber = 13.24
print(get_pos_float(decimalNumber, 10)) # prints the tenths decimal position 2
print(get_pos_float(decimalNumber, 100)) # prints the hundredths decimal position 4
print(get_pos_float(decimalNumber, 1000)) # prints the thousandths decimal position 0
rouble
  • 16,364
  • 16
  • 107
  • 102