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?

1
  • 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). Commented Jun 24, 2021 at 23:26

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.