0

I'm sorry, I know this must be a duplicate, I can't find where else it's posted. Please feel free to link me to the original question and mark this as duplicate.

I would like to print a 3 digits of a number AFTER the decimal point in it. For example:

number = 523.637382

I would like to print: 523.637 I have a feeling I can use something similar to this

print(str(number)[:7])
>>>523.637

However, this will not work if the number before the decimal is not 3 decimals.

Bonus points: Would this be easy?

number = 500.220
#magic
>>>500.22

number = 500.2000003
#magic
>>>500.2
Kyle Me
  • 336
  • 2
  • 5
  • 13
  • In Java you can format a string using placeholder like %.2f etc. to change how much decimals/width/etc should have the output variable... maybe in python exists something similar? – Marco Acierno Aug 12 '14 at 01:36

3 Answers3

2

A (built-in) function that could do this is round:

>>> number = 523.637382
>>> rounded = round(number, 3) # 3 decimal places, for example
>>> rounded
523.637

This has already been answered for example here.

The good news, to answer the second part of your question, is that the round function automatically removes trailing zeroes. It's much harder to retain the zeros if you're defining a new variable: you need the decimal module; but it looks that that isn't necessary here.

>>> number = 523.60000001
>>> rounded = round(number, 3)
>>> rounded
523.6
Community
  • 1
  • 1
Ewharris
  • 164
  • 3
2
print("%.3f" % number)

or, using the new-style formatting,

print("{0:.3f}".format(number))
MattDMo
  • 100,794
  • 21
  • 241
  • 231
0

If you're printing a str like above you can use string interpolation:

number = 33.33333
print("{0:.3f}".format(number))
#=> 33.333
agconti
  • 17,780
  • 15
  • 80
  • 114