1

I want to transform this:

my_number = 3.1415928

if precision == 2:
    my_string = "{0:.2f}".format(my_number)
elif precision == 3:
    my_string = "{0:.3f}".format(my_number)
elif precision == 4:
    my_string = "{0:.4f}".format(my_number)
elif precision == 5:
    my_string = "{0:.5f}".format(my_number)

Into something like this:

my_number = 3.1415928

my_string = "{SOMETHING_DEPENDING_ON_PRECISION_HERE}".format(my_number)

Is it possible and how to do it?

0

1 Answer 1

4

in addition to Vaultah's (excellent) suggestion you can do it with the splat with old style formating as well

precision = 2
my_num = 3.1415928
my_string = "%0.*f"%(precision,my_num)

Vaultah's (now shredded suggestion)

"{0:0.{prec}f}".format(my_num,prec=precision)
Sign up to request clarification or add additional context in comments.

2 Comments

What if I wanted the minimum number of decimals necessary?
use "%g" and it will truncate non-meaningful digits

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.