Python Forum
Rounding/Truncating Numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Rounding/Truncating Numbers (/thread-15422.html)



Rounding/Truncating Numbers - Trinx - Jan-16-2019

How do I format a variable to a standard money format? This is what I am currently doing:

total = 214.5467
print('Your total is: $' + str(total)[0:4])
Problem is, it only puts out 3 digits, meaning most of the number will be ignored. What commands do I need to use to fix this?


RE: Rounding/Truncating Numbers - Larz60+ - Jan-16-2019

use:
print('Your total is: $ {:4.6f}'.format(total))
the .6 tells format to use 6 decimal places to right the 4, 4 on left 'f' = float


RE: Rounding/Truncating Numbers - snippsat - Jan-16-2019

Use f-string.
>>> total = 214.5467
>>> print(f'Your total is: $ {total:.2f}')
Your total is: $ 214.55

>>> for word in 'f-strings are awesome'.split():
...     print(f'{word.capitalize():~^20}')
...     
~~~~~F-strings~~~~~~
~~~~~~~~Are~~~~~~~~~
~~~~~~Awesome~~~~~~~



RE: Rounding/Truncating Numbers - Trinx - Jan-16-2019

(Jan-16-2019, 10:24 PM)Larz60+ Wrote: use:
print('Your total is: $ {:4.6f}'.format(total))
the .6 tells format to use 6 decimal places to right the 4, 4 on left 'f' = float

(Jan-16-2019, 10:39 PM)snippsat Wrote: Use f-string.
>>> total = 214.5467
>>> print(f'Your total is: $ {total:.2f}')
Your total is: $ 214.55

>>> for word in 'f-strings are awesome'.split():
...     print(f'{word.capitalize():~^20}')
...     
~~~~~F-strings~~~~~~
~~~~~~~~Are~~~~~~~~~
~~~~~~Awesome~~~~~~~

Wow! Thanks for the advice guys. I had never heard of an f-string before. I finally got a script I've been working on finished with your advice. Big Grin

Output:
~~~~~~~~You~~~~~~~~~ ~~~~~~~~Guys~~~~~~~~ ~~~~~~~~Are~~~~~~~~~ ~~~~~~Awesome!~~~~~~