Search code examples
pythonpython-3.xf-string

Is there a way to strip digits before the decimal place from a float using f-string?


I'm trying to solve the following challenge:

  • Write a function that takes a float and two integers (before and after).
  • The function should return a float consisting of before digits before the decimal place and after digits after.
  • Thus, if we call the function with 1234.5678, 2, 3 the return value should be 34.567

I have a version that works without f-strings as it stands, and I'm wondering if there's a better way of doing it using f-strings instead.

def eitherSide(someFloat, before, after)  :
    bits  = str(someFloat).split('.')
    bit1 = bits[0][:-before]
    bit2 = bits[1][:after]
    num = float(bit1 + '.' + bit2)
    return print(num)

Thanks!


Solution

  • I don't think it would make mathematical sense to strip digits from the integer part of a float. but fstring allow you to format the decimal part easily with something like print(f"{value:.3f}")

    if you really want to use fstring you could do :

    def eitherSide(someFloat, before, after)  :
        left, right = str(someFloat).split('.')
        return f"{left[-before:]}.{right[:after]}"