3

I have three floats that I want to output as a 2 decimal places string.

amount1 = 0.1
amount2 = 0.0
amount3 = 1.87

I want to output all of them as a string that looks like 0.10, 0.00, and 1.87 respectively.

How do I do that efficiently?

1 Answer 1

5

An alternative to directly formatting them is the locale stdlib module

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123.2342343234234234)
'$123.23'
>>> locale.currency(123.2342343234234234, '')  # the second argument controls the symbol
'123.23'

This is nice because you can just set the locale to the users default as I do and then print in their conventions.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.