0

I currently am trying to work with a number that has variable decimal place lengths. It can either be an integer, or have up to 10 decimals i.e. 33.3333333. I wanted to restrict the number to only have 2 decimals when it exceeds the length, or maintain the original if it's less.

I've tried using "{:0:.2f}".format, but the problem is that for integers, it also adds .00 to the end of the string.

When I tried using round(3) it'll return 3.0.

Is there a method, preferably a single line, that can convert 3.333333 to 3.33 but still allow for 3 to stay as an int?

martineau
  • 119,623
  • 25
  • 170
  • 301
Kevin Yao
  • 65
  • 2
  • 7
  • 1
    Are you using Python 2? Because `round(3)` returns `3`, not `3.0`, in Python 3. You should probably upgrade (Python 2 hit end of life a year and a half ago). – ShadowRanger Jun 24 '21 at 23:26

2 Answers2

1

Try choosing the format as a function of the values wholeness:

"{d}" if int(a) == a else "{:0:.2f}"

Can you finish from there?

Prune
  • 76,765
  • 14
  • 60
  • 81
1

You can use a conditional expression to choose the format based on the type of the variable:

for x in (33.3333333, 3):
    print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))

You could also implement it using a dictionary to map types to format strings:

formats = {int: "{:0}", float: "{:.2f}"}

for x in (33.3333333, 3):
    print(formats.get(type(x)).format(x))
martineau
  • 119,623
  • 25
  • 170
  • 301