'Round number down to the next 1000 in python [duplicate]
can somebody tell me how i can round down to the nearest thousand. So far I tried it with math.round(), the truncate function but i couldn't find my math skills to work out for me. As a example for some people I want that 4520 ends up in beeing 4000.
Solution 1:[1]
In Python, you can do
print((number // 1000)*1000)
Solution 2:[2]
just a thought
Why not do it the traditional way?!
deprecate_vals = 3
val = 4520
val = int(val/(10**deprecate_vals)) * (10**deprecate_vals)
print(val)
Solution 3:[3]
You can divide by 1000 before rounding and then multiply by 1000.
invalue = 4320
outvalue = 1000 * round(invalue/1000)
print("invalue: ",invalue)
print("rounded value: ",outvalue)
output
invalue: 4320
rounded value: 4000
Solution 4:[4]
There is multiple way to do it.
You can get the digit for the thousand by using the division (// mean without remaining, so you don't get 4,52 but 4)
x = 4520
rounded_x = (x//1000) * 1000
You can also use the remaining of the division with the modulo operator and remove it to the value :
x = 4520
rounded_x = x - (x%1000)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Senthil |
Solution 2 | High-Octane |
Solution 3 | |
Solution 4 | Xiidref |