0

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
bers
  • 4,817
  • 2
  • 40
  • 59
  • Does this answer your question? [How to round a number to significant figures in Python](https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python) – The Thonnu Sep 27 '22 at 18:53
  • @TheThonnu I should have noted that I would not like to round the integer part - 1234.56 should remain 1234, not 1000 as in the other question. – bers Sep 27 '22 at 18:56

2 Answers2

1

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
    
  • 1
    This uses scientific notation for `f = 0.00000123`, but maybe I just need to accept that. – bers Sep 27 '22 at 19:54
0

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
bers
  • 4,817
  • 2
  • 40
  • 59