减少显示大数但不显示小数的小数

Reduce decimals shown for large numbers but not for small

格式化浮点数时,有没有pythonmethod/formatting减少数字变大时显示的小数位数?

例如,它可以限制显示的数字位数。示例如下:

 100.145 ->  100
   2.392 ->    2.39
  34.827 ->   34.8
4599.298 -> 4599

更新:

正如 chux 在他的评论中指出的那样,我原来的解决方案不适用于 舍入导致进位的边界情况。还有,我没注意 log10(100) == 2 != 3 的事实。 第二个错误很容易出现。为了修复第一个,我想出了一个 递归。现在它应该可以工作了,但不再简单了。

import math

def flexible_format(num_in, total_digits):
    try:
        digits_before_decimal = math.floor(math.log10(abs(num_in))) + 1
    except ValueError:
        # if num == 0
        return '0'
    digits_after_decimal = max(0, total_digits - digits_before_decimal)
    # if rounding increases number of digits, we have to format once again
    # after that, an additional rounding doesn't increase the number of digits
    # so we can be sure not to land in an infinite recursion 
    num_out = round(num_in, digits_after_decimal)
    if math.floor(math.log10(abs(num_out))) >= digits_before_decimal:
        return flexible_format(num_out, total_digits)
    return f'{num_out:.{digits_after_decimal}f}'

list_nums =  [-100.145,  2.392, -34.827 , 4599.298, 99.95, 100 ]
for num in list_nums:
    print(flexible_format(num, total_digits=3))
 
# -100
# 2.39
# -34.8
# 4599
# 100
# 100

原假解法:

我不知道实现该功能的常用函数,但很容易实现。

import math

def flexible_format(num, total_digits):
    try:
        digits_before_decimal = math.ceil(math.log10(abs(num)))
    except ValueError:
        # if num == 0
        return '0'
    digits_after_decimal = max(0, total_digits - digits_before_decimal)
    return f'{num:.{digits_after_decimal}f}'

list_nums =  [-100.145,  2.392, -34.827 , 4599.298, 0]

for num in list_nums:
    print(flexible_format(num, total_digits=3))

# -100
# 2.39
# -34.8
# 4599
# 0