简体   繁体   English

如何将浮点数格式化为 x 有效数字

[英]How to format floating-point number to x significant digits

I am looking to print a floating-point number to a number of significant digits, where I consider digits in front of the decimal separator as significant.我希望将浮点数打印为多个有效数字,我认为小数点分隔符前面的数字是有效的。 So with 3 significant digits, I would like the following:因此,使用 3 位有效数字,我想要以下内容:

1234.56 --> 1234
123.456 --> 123
12.3456 --> 12.3
1.23456 --> 1.23
.123456 --> 0.123
.012345 --> 0.0123
.0012345 --> 0.00123

Basically, I want to suppress the decimal fraction if it is not required, but I do not want to round the integer part.基本上,如果不需要,我想抑制小数部分,但我不想舍入 integer 部分。 (And I would like to avoid scientific notation.) (而且我想避免使用科学记数法。)

How can I achieve that?我怎样才能做到这一点? I tried a number of ways, but none really do what I want.我尝试了很多方法,但没有一个能真正做到我想要的。

This is close, but uses scientific notation:这很接近,但使用科学记数法:

for x in [1234.56, 123.456, 12.3456, 1.23456, .123456, .012345, .0012345]:
    print(x, " --> ", f"{x:.3g}")

1234.56  -->  1.23e+03  # wrong!
123.456  -->  123
12.3456  -->  12.3
1.23456  -->  1.23
0.123456  -->  0.123
0.012345  -->  0.0123
0.0012345  -->  0.00123

In such conditions you can try like this在这种情况下,您可以尝试这样

for f in [1234.56, 123.456, 12.3456, 1.23456, .123456, .012345, .0012345]:

    dp= str(f)[::-1].find('.')
    #print(dp)
    if dp <=3:

        fs= int(f)
        print(f, "-->",fs)
    else:
        print(f, " --> ", f"{f:.3g}")

output: output:

1234.56 --> 1234
123.456 --> 123
12.3456  -->  12.3
1.23456  -->  1.23
0.123456  -->  0.123
0.012345  -->  0.0123
0.0012345  -->  0.00123
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM