代码之家  ›  专栏  ›  技术社区  ›  shayelk

用一组有效数字打印浮点数(非科学)

  •  2
  • shayelk  · 技术社区  · 7 年前

    e ).

    例如,这个数字 0.000000002343245345 应打印为 0.000000002343 (而不是 2.343e-09 )

    >>>print('{:.3e}'.format(0.000000002343245345))
    2.343e-09
    

    以及如何在不使用电子记数法的情况下打印一组小数位:

    >>>print('{:.12f}'.format(0.000000002343245345))
    0.000000002343
    

    但不是如何把两者结合起来。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Rory Daulton    7 年前

    这里有一些代码通常可以满足您的需要。

    x = 0.000000002343245345
    n = 4
    
    from math import log10, floor
    
    print('{:.{}f}'.format(x, n - floor(log10(x)) - 1))
    

    floor(log10()) 可能与预期的10次方或非常接近的10次方差一次,例如 0.1 , 0.01 , 0.001

    而且,对于某些组合 x n x = 200000 n = 4

    ValueError: Format specifier missing precision
    
        2
  •  2
  •   Daniel    7 年前

    你必须自己计算数字的数目。对于四个有效数字,这将是

    number = 0.000000002343245345
    digits = 4 - int(math.ceil(math.log10(number)))
    print("{:.{}f}".format(number, digits))
    # 0.000000002343
    
    推荐文章