Yehudah
Yehudah

Reputation: 65

How can I convert a string to a float and always show 2 decimal places?

I've managed to get 2dp format for a number, however, it returns a string. Is there any way to keep float and always have 2dp regardless if there are instances of .00?

average = "{:.2f}".format(10.0)
print(average)

Outputs

'10.00'

However, if I try to convert this to a float using the following

average = float("{:.2f}".format(10.0))

It outputs the following float:

10.0

I've seen other threads that say to use Decimal, but i'm uncertain of how to do this without importing library.

Is there anyway to achieve this without importing any libraries?

Upvotes: 0

Views: 165

Answers (1)

Abdulaziz
Abdulaziz

Reputation: 3426

Keep it as a float the entire time, at the last step when you want to show it covert it to string with two decimal points. This is not the perfect answer but it will work.

Upvotes: 1

Related Questions