【问题标题】:Format real number to maintain decimal separator position and number of decimal places when printing打印时格式化实数以保持小数分隔符位置和小数位数
【发布时间】:2021-12-10 12:44:07
【问题描述】:

我想在日志中输出温度,值在 0 到 30 之间。我希望小数点分隔符在行之间对齐,并且小数位数要固定,例如:

a =  7.56, s = 20.00
a = 21.03, s = 20.00    
a = 20.01, s = 20.00
a =  1.10, s =  5.00

实际数字可能不合理,应在小数点后四舍五入至两位。理想情况下,我想使用 f-strings 来提高代码的可读性,但任何其他格式规范也可以。我可以实现这一点,而无需自己舍入和生成字符串吗?到目前为止,我所有的尝试(和谷歌搜索)都失败了:我无法固定小数点后的位数。

【问题讨论】:

标签: python format f-string


【解决方案1】:

无经验:

def print_numbers(numbers):
    for couple in numbers:
        print("a = %6.2f,   b = %6.2f" % (couple[0],couple[1])) 

numbers = [(7.56000,20.0000),(21.030,20.000),(20.0100000,20.000000),(1.1000,5.000)]
print_numbers(numbers)

输出:

a =   7.56,   b =  20.00
a =  21.03,   b =  20.00
a =  20.01,   b =  20.00
a =   1.10,   b =   5.00

格式%:

%s - Stringa (o qualsiasi oggetto che possa essere rappresentato con una stringa, ad esempio numeri)
%d - Interi
%f - Numeri reali/virgola mobile
%.<number of digits>f - Numeri in vigola mobile con un un numero fisso di cifre decimali.
%x/%X - Rappresentazione esadecimale di numeri interi (minuscolo/maiuscolo)

es. %-8.3d    (- -> allineamento a sinistra, 8 -> campo minimo di 8 colonne, 3 -> cifre decimali, d -> tipi interi) 

【讨论】:

    【解决方案2】:

    这里是函数formatted,它有助于按十进制值对齐。

    加号:如果数字大于捐赠的空间,则会出现点:

    def main():
        numbers = [1.2345, 12.345, 123.45, 1234.5]
        for number in numbers:
            print(formatted(number, 4, 3))
    
    def formatted(value, int_places=2, dec_places=2):
        total_places = int_places + dec_places + 1
        formatted_value = f'{value:{total_places}.{dec_places}f}'
        if len(formatted_value) > total_places:
            return '.' * total_places
        else:
            return formatted_value
    if __name__ == "__main__":
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2018-01-26
      • 2013-05-04
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多