0

Ok, please bear with me, I'm completely new to this. This is for school, and the exact syntax isn't important here for my assignment, but for my own personal knowledge I want to know a little more about string formatting.

whenever I use %f it defaults to 2 decimal places. Is there a string format that I can use on a float that will show the float with the number of decimals it actually has?

for instance my list contains 2.0, 2.01, 2.001, 2.0001 and I want to use a string format to print them as they look. Which format code would I use or how could I use %f properly if possible?

This is in Python 2.7 on Windows 7(if that matters).

Jon Clements
  • 138,671
  • 33
  • 247
  • 280

2 Answers2

0

If you convert the float to a string, then when you print it, it will be displayed just as you wrote it.

>>> x = str(2.0)
>>> print(x)
2.0
>>> x = str(2.01)
>>> print(x)
2.01
>>> x = str(2.001)
>>> print(x)
2.001
>>> x = str(2.0001)
>>> print(x)
2.0001

(In fact, to be precise, in Python you're not actually converting the floating point object, but creating a string object that looks like it. But that's a bit outside of the scope of your question.)

UPDATE

Someone posted a way to remove trailing zeros from floating point numbers using the Decimal class, here: Removing Trailing Zeros in Python

Community
  • 1
  • 1
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • I could do that, but I was hoping there was a one line print statement I could use. print '%f,%f,%f' % (2.0,2.01,2.001) returns 2.000000,2.010000,2.001000. Which is weird because a couple days ago it defaulted to 2 decimal places. But anyways, is there a modifier to remove the trailing 0's? – user2243208 Apr 10 '13 at 04:32
  • Here's a one line print statement that works: `print(','.join((str(2.0),str(2.01),str(2.001),str(2.0001))))` – twasbrillig Apr 10 '13 at 08:11
  • I also updated the above answer with a link to a function someone wrote that drops the trailing zeros from floating point values. If my answers are helpful, please check the box to accept the answer. Thanks! – twasbrillig Apr 10 '13 at 08:17
  • That will be very useful for another project I'm working on, but a lot more complex than what I'm trying to do here. And I guess removing the "trailing" zeros wasn't the correct idea when I said it. – user2243208 Apr 11 '13 at 04:16
0

%g may be what you're looking for:

>>> "%g, %g, %g, %g" % (2.1, 2.01, 2.001, 2.0001)
'2.1, 2.01, 2.001, 2.0001'
Elmar Peise
  • 14,014
  • 3
  • 21
  • 40