7
7
700ghz2016-03-18 16:01:57
Python
700ghz, 2016-03-18 16:01:57

Python: format str float - how to hide the fractional part if it is zero?

Python3.4.
It is necessary to form a line with a price.
If the fractional part of the price is 0, then do not display it (the fractional part).


  1. >>> floatVal = 123.456
    >>> "Price: {:.2f}".format(floatVal)
    'Price: 123.46'

  2. >>> floatVal = 123.00
    >>> "Price: {:.2f}".format(floatVal)
    'Price: 123.00'

The fractional part is displayed in both cases. And in the second case, you need to get the string 'Price: 123'
What should the format string be?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Klimenko, 2016-03-18
@700ghz

>> from decimal import Decimal
>>> quantize = Decimal('.01')
>>> print(Decimal(123.456).quantize(quantize).normalize())
123.46
>>> print(Decimal(123.00).quantize(quantize).normalize())
123

A
abcd0x00, 2016-03-23
@abcd0x00

The price must be stored as an integer, otherwise it may become unreliable due to rounding.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question