default print format for floats
Batista, Facundo
FBatista at uniFON.com.ar
Mon Mar 1 14:12:30 EST 2004
beliavsky wrote:
#- By default, Python prints many floating point numbers with 17 digits
#- after the decimal place. I would like to make the DEFAULT 4 decimal
#- places. Is this possible?
#-
#- For example, the code
#-
#- from string import join
#- x = [1.0,0.3,0.4]
#- print x
#- print join(["%4.1f" % y for y in x])
#-
#- gives the output
#-
#- [1.0, 0.29999999999999999, 0.40000000000000002]
#- 1.0 0.3 0.4
#-
#- I want the simplicity of "print x", without so many decimal places.
You can inheritate and overload:
The code...
class MyFloat(float):
def __str__(self):
return "%1.4f" % self
def __repr__(self):
return "%1.4f" % self
a = 0.3
print "Just a float:", a
mf = MyFloat(0.3)
print "My Float:", mf
x = [1.0,0.3,0.4]
print "A list of floats:", x
x = map(MyFloat,[1.0,0.3,0.4])
print "A list of myfloats:", x
...produces the following output:
Just a float: 0.3
My Float: 0.3000
A list of floats: [1.0, 0.29999999999999999, 0.40000000000000002]
A list of myfloats: [1.0000, 0.3000, 0.4000]
Note that in the first two lines, we're using the overload of __str__, and
in the last to, the overload of __repr__.
. Facundo
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
ADVERTENCIA
La información contenida en este mensaje y cualquier archivo anexo al mismo,
son para uso exclusivo del destinatario y pueden contener información
confidencial o propietaria, cuya divulgación es sancionada por la ley.
Si Ud. No es uno de los destinatarios consignados o la persona responsable
de hacer llegar este mensaje a los destinatarios consignados, no está
autorizado a divulgar, copiar, distribuir o retener información (o parte de
ella) contenida en este mensaje. Por favor notifíquenos respondiendo al
remitente, borre el mensaje original y borre las copias (impresas o grabadas
en cualquier medio magnético) que pueda haber realizado del mismo.
Todas las opiniones contenidas en este mail son propias del autor del
mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones
Personales S.A. o alguna empresa asociada.
Los mensajes electrónicos pueden ser alterados, motivo por el cual
Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación
cualquiera sea el resultante de este mensaje.
Muchas Gracias.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20040301/2bc887ea/attachment.html>
More information about the Python-list
mailing list