有没有办法使用 f-string 从浮点数中去除小数点前的数字?

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

我正在尝试解决以下挑战:

编写一个函数,接受一个 float 和两个整数(beforeafter) .该函数应该 return 一个由小数点前 before 位数字和小数点后 after 位数字组成的浮点数。因此,如果我们用 1234.5678, 2, 3 调用函数, return 值应该是 34.567

我有一个没有 f-strings 的版本,我想知道是否有更好的方法使用 f-strings 代替。

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

谢谢!

使用一些数学和 f 字符串:

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

然而,这不会截断,而是舍入。

我认为从浮点数的整数部分去除数字在数学上没有意义。 但是 fstring 允许您使用 print(f"{value:.3f}")

之类的格式轻松格式化小数部分

如果你真的想使用 fstring 你可以这样做:

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