2

How would I be able to round numbers like these to two decimal places which are all stored in a variable which has been outputted by a web scraper:

4.7532
4.7294
4.7056
4.6822857142857
4.65868
4.63522
4.6119866666667
4.58898
4.566064
4.543216

I am new to python so i'm not sure. I'm using Python 2

2
  • 2
    you have a builtin fun round() Dec 20, 2014 at 3:40
  • Just one personal thought, use Python 3.
    – nbro
    Dec 20, 2014 at 3:53

2 Answers 2

7

Use the built-in function round(), example:

>>> round(4.7532,2)
4.75
>>> round(4.7294,2)
4.73
4
  • TypeError: a float is required, I'm not sure what this means?
    – Ando
    Dec 20, 2014 at 3:42
  • @Ando make sure the type of your variable is float, if it's a string (ex: num='4.7532'), convert it to float number first and pass to round(): round(float(num),2)
    – Paul Lo
    Dec 20, 2014 at 3:45
  • @Ando float is a built-in numeric type in python. The function round() only accepts floats or integers as input. You get an error message when you try this round("3.14") instead of round(3.14)
    – Håken Lid
    Dec 20, 2014 at 4:44
  • 4
    Python 3 has a more helpful error message: TypeError: type str doesn't define __round__ method
    – Håken Lid
    Dec 20, 2014 at 4:47
1

I think from what you say, you have a single string containing these numbers, and you want to print them out as 2dp formatted?

If so, the first thing to do is split the single string into an array, and convert to floating point numbers

numstr = """4.7532
4.7294
4.7056
4.6822857142857"""

nums = [float(x) for x in numstr.split("\n")]

This gives us an array of floating point python numbers

Now, we want to output them, having rounded. We can do that a few ways, the easiest is probably

for num in nums:
    print "%0.2f" % num

That will loop over all your numbers, and print them out one per line, formatted to two decimal places

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.