Home > database >  How to format floating-point number to x significant digits
How to format floating-point number to x significant digits

Time:09-28

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:

1234.56 --> 1235  # edited that - I think 1234 is not what I want here
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. (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

CodePudding user response:

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:

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
    

CodePudding user response:

This works nicely:

import numpy as np

MIN_DIGITS = 0
SIGN_DIGITS = 3

for x in [1234.56, 123.456, 12.3456, 1.23456, 0.123456, 0.012345, 0.0012345]:
    print(
        x,
        "-->",
        np.format_float_positional(
            x,
            precision=max(SIGN_DIGITS - int(np.ceil(np.log10(x))), MIN_DIGITS),
            trim="-",
        ),
    )

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

And with MIN_DIGITS = 1:

1234.56 --> 1234.6
123.456 --> 123.5
12.3456 --> 12.3
1.23456 --> 1.23
0.123456 --> 0.123
0.012345 --> 0.0123
0.0012345 --> 0.00123
  • Related