0

I am looking to get the variable "a" to two decimal places. I have achieved it using the .format method. However to keep inline with the code I have been using %d. How can I get the variable "a" to two decimal places using %d or is it even possible this way?

a = 10.5678

print("The result is {:.2f} in volts".format(a))
print("The result is %d, in volts" % (a))
Aaron Mc
  • 1
  • 3
  • 2
    Use `print("The result is %.2f, in volts" % (a))` – Ch3steR May 24 '20 at 12:35
  • An answer here notes that %d uses int(): https://stackoverflow.com/questions/4288973/whats-the-difference-between-s-and-d-in-python-string-formatting#4288983 , so you have to use %.2f, as noted above. – asylumax May 24 '20 at 12:41
  • What does "to keep inline with the code" mean? It's not clear why you want to use `%d`, but it's the wrong tool for the job.] – Mark Dickinson May 24 '20 at 13:07
  • Sorry if I am using the wrong terms, i am relatively new to python. This is just a snippet of the overall code from a little project i am working on. Instead of using {} .format for strings in my project for example i am using %s. so I just wanted to keep the same for floats – Aaron Mc May 24 '20 at 13:53

1 Answers1

1

Why not use f string

print(f"The result is {a:.2f}, in volts")