0

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!

05c4r2009
  • 11
  • 1

2 Answers2

1

Using some math and f-strings:

def eitherSide(someFloat, before, after):
    return f"{someFloat % 10**before:.{after}f}"
    # return float(f"{sf:.{after}f}")  
    # seems weird to possibly lose the representation again

This will however, not truncate, but round.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

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]}"