24 | def float_str(f, min_digits=2, max_digits=6): |
25 | """ |
26 | Returns a string representing a float, where the number of |
27 | significant digits is min_digits unless it takes more digits |
28 | to hit a non-zero digit (and the number is 0 < x < 1). |
29 | We stop looking for a non-zero digit after max_digits. |
30 | """ |
31 | if f >= 1 or f <= 0: |
32 | return str(round_float(f, min_digits)) |
33 | start_str = str(round_float(f, max_digits)) |
34 | digits = start_str.split(".")[1] |
35 | non_zero_indices = [] |
36 | for i, digit in enumerate(digits): |
37 | if digit != "0": |
38 | non_zero_indices.append(i + 1) |
39 | |
40 | if len(non_zero_indices) == 0: |
41 | num_digits = min_digits |
42 | else: |
43 | |
44 | min_non_zero_indices = range(non_zero_indices[0], non_zero_indices[-1] + 1)[:min_digits] |
45 | num_digits = min_non_zero_indices[-1] |
46 | return str(round_float(f, num_digits)) |