How to round numbers

后端 未结 2 979
粉色の甜心
粉色の甜心 2021-01-22 02:58

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         


        
相关标签:
2条回答
  • 2021-01-22 03:04

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

    >>> round(4.7532,2)
    4.75
    >>> round(4.7294,2)
    4.73
    
    0 讨论(0)
  • 2021-01-22 03:09

    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

    0 讨论(0)
提交回复
热议问题