0

I need to display trailing zeros in a decimal number. I have consider using python format() but it returns a string and when I convert it to float or decimal the trailing zero disappears.

I have also tried using python decimal but it returns a Decimal instance on variable assignment. For example:

>>> x = decimal.Decimal(format(15.2, '.2f'))
>>> print x
15.20
>>> x
Decimal('15.20')

Python version: 2.7

I need to display 15.2 as 15.20 (not as '15.20' << string type)

Thanks In Advance

akhi1
  • 1,322
  • 1
  • 16
  • 25
  • 5
    What is wrong with it returning it as a string? You certainly can display that and the trailing zeros will appear. – wallyk Feb 23 '17 at 06:56
  • @wallyk Its a part of my django app where the api returns some json data and my front end is expecting float or decimal. If i could directly obtain the expected decimal value then it could help me reduce some operations performed at front end. – akhi1 Feb 23 '17 at 07:02
  • 3
    You cannot do this. Floating point number representation does not include trailing zeros. – DYZ Feb 23 '17 at 07:05
  • @DYZ Is there any way i could get value from decimal instance code shown above? as shown by >>> print x – akhi1 Feb 23 '17 at 07:10
  • Sure: `float(x)`. But whatever value you get, is going to be a floating-point number. – DYZ Feb 23 '17 at 07:14

1 Answers1

0

You can create a float subclass that behaves this way:

class RoundFloat(float):
    def __new__(cls, value=0, places=2):
        return float.__new__(cls, value)
    def __init__(self, value=0, places=2):
        self.places = str(places)
    def __str__(self): 
        return ("%." + self.places + "f") % self
    __repr__ = __str__

Usage:

pi = RoundFloat(3.1415927, places=4)
print pi         # 3.1416

It may be convenient to leave off the __repr__ so you can easily get the full value if you need it using repr(x).

kindall
  • 178,883
  • 35
  • 278
  • 309
  • I thought you wanted decimals, not float. I'd look at this SO question: http://stackoverflow.com/a/3148376/1904113 – MKesper Feb 23 '17 at 07:31