I'm writing a method to generated a latex table table from input arrays. It's working but there is one nuisance: I want trailing zeros on numbers. Right now I'm using the %g method which works nicely, but it still will turn 1.340 into 1.34 if I do "%.4g" % 1.340. Is there any python method that anyone knows of that will keep trailing zeros out to a given decimal place? Any ticks I can do to format the numbers this way and just use %s?

TIA,

Dave

why not `"%.3f"` ?

I chose a poor example -- I need the method to be able to handle very large/small numbers as well -- the current application I'm using this for involves determinations of Planck's constant, about 6e-34. %f would give nasty results for that :)

So more specifically, I'd need something that will take 6.340024e-34 and if I specify 4 sigfigs, it will output 6.340e-34 instead of 6.34e-34

I suppose that's what this comes down to -- some way of handling significant figures instead of just arbitrary rounding.

Aha -- I just needed to rtfm a bit more clearly. In the fine print on http://docs.python.org/lib/typesseq-strings.html, it says the alternate form (with the # flag) gives this behavior, so:

``````>>> print "%#.4g" % 6.340024e-34
6.340e-34``````

I've been looking for this solution for so long, I'm beside myself right now :)

commented: Thanks for keeping in touch +2

Aha -- I just needed to rtfm a bit more clearly. In the fine print on http://docs.python.org/lib/typesseq-strings.html, it says the alternate form (with the # flag) gives this behavior, so:

``````>>> print "%#.4g" % 6.340024e-34
6.340e-34``````

I've been looking for this solution for so long, I'm beside myself right now :)

Thanks for letting all of us know!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.