I need to know what the command is for setting a specific set of decimal places in an answer, somewhat like the PHP number_format command.

Here is what I got coming up in my answer....


I need it so it says:


Anyone have an idea of what the code is to perform this?

7 Years
Discussion Span
Last Post by snippsat

http://www.daniweb.com/forums/thread162126.html a=round(0.7893948, 3) if you only want to print it so, you can do print "%.3f" % 0.7893948 You can use this also to prepare result as string s= "%.3f" % 0.7893948 This answers are with 0 not with . only. That you must check separately for example

>>> n=0.7893948
>>> s=round(n,3)
>>> if abs(s)<1: print ("%.3f" % s)[1:]
else: "%.3f" % s

Edited by pyTony: n/a


That works, but i need to eliminate the zero on the left side of the decimal point. How about do I do that? I have the user entering their attempts to bat and their hits so it isn't an automatic "average", it depends on the input. Sorry for not mentioning earlier.

Edited by johnnyd1986: n/a


If it`s a number python will output as 0.something
You can remove 0 by make it a string.

>>> n = 0.7893948
>>> print n
>>> n = str(n)
>>> n
>>> n = n.replace('0', '')
>>> n
>>> #if we make it an integer(float) again,it will output the 0
>>> n = float(n)
>>> n
>>> import re
>>> re.sub('^0+', '', '0.7893948')

Maybe you have to think diffrent i dont think that 0 will be a problem.
Post you code if you dont get it to work,so can we look at it.

Edited by snippsat: n/a


As I wrote before like this (python 2)

s=number to convert

>>> s=0.345
>>> if abs(s)<1: a=("%.3f" % s)[1:]
else: a= ("%.3f") % s

>>> print a

Edited by pyTony: n/a


It still still a string tonyjv.
Use this to check type(a)

Just a and enter.

If he shall use it to calulate,he need it to make it a float.
a + a

Edited by snippsat: n/a


Except for this small thing

>>> float(.345)

Not in three decimals as long as it is not string.

Edited by pyTony: n/a


Yes off course,i did the same in my code if look at my post.

If it`s a number python will output as 0.something

If you make it a integer/float then the "0. " is there.
That why i said if 0 shall be removed make it a string.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.