dijxtra
dijxtra

Reputation: 2751

format float with minimum and maximum number of decimals

I'd like to format a float with minimum 2 and maximum 8 decimals. I do it like this:

def format_btc(btc):
    s = locale.format("%.8f", btc).rstrip('0')
    if s.endswith(','):
        s += '00'
    return s

Is there a way to do it only with format() function?

edit:

examples: left is float, right is string

1 -> 1,00
1.1 -> 1,10 (I have now realised that my code returns 1,1 for this example; that's a bug)
1.12 -> 1,12
1.123 -> 1,123
1.12345678 -> 1,12345678
1.123456789 -> 1,12345678
1,1234567890 -> 1,12345678

Upvotes: 1

Views: 124

Answers (1)

Terry Jan Reedy
Terry Jan Reedy

Reputation: 19144

No. I rechecked the specification language to make sure. Possible reasons:

  1. (Theoretical) If 8 digits after decimal are significant, then deleting 0s deletes information.

  2. (Practical) The complication of adding a third number argument used only for floats and then very seldom is not work the rare gain.

Upvotes: 1

Related Questions