Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round numbers to the nearest 1000?

I'm having some issue to round up and down of a list of number to the nearest 1000.

Below is my code:

rev_list = []

for i in range(12):
    rev = int(round(random.normalvariate(100000, 12000)))
    rev_list.append(rev)

print(rev_list)

The output is:

[97277, 96494, 104541, 132060, 98179, 87862, 84718, 95391, 94674, 89773, 92790, 86122]

I would like to round the list to the nearest 1000. How can I do that?

like image 290
123cremepie Avatar asked Sep 29 '17 03:09

123cremepie


People also ask

What is 4725 rounded to the nearest 1000?

4,725 to the nearest 1,000 is 5,025 Page 9 A number is shown in the place value chart.

What is 3500 rounded to the nearest 1000?

We will change the digit in hundreds places to 0 and add 1 to the digit in thousands places. So, the nearest thousand to 3500 is 4000.


2 Answers

The round function can take negative digits to round to, which causes it to round off to the left of the decimal. For example:

>>> round(15768, -3)
16000
>>> round(1218, -3)
1000

So the short answer is: Call round with the second argument of -3 to round to the nearest 1000.

like image 117
ShadowRanger Avatar answered Oct 04 '22 03:10

ShadowRanger


List comprehension is a one-line loop which allows you to apply a function to the list items. (for more read List Comprehensions)

[x for x in rev_list]

In this case, round(num, -3) is the function.

>>> round(1300,-3)
1000
>>>

The answer

You can apply a function on a list by this code

rev_list=[round(x,-3) for x in rev_list]

The example:

>>> rev_list=[97277, 96494, 104541, 132060, 98179, 87862, 84718, 95391, 94674, 89773, 92790, 86122]
>>> rev_list=[round(x,-3) for x in rev_list]
>>> rev_list
[97000, 96000, 105000, 132000, 98000, 88000, 85000, 95000, 95000, 90000, 93000, 86000]
>>>
like image 33
Reza energy Avatar answered Oct 04 '22 01:10

Reza energy