I am wondering how can I floor 1,999,999
to 1,000,000
or 2,000,108
to 2,000,000
in python?
I used math.floor()
but it's just for removing decimal part.
Asked
Active
Viewed 327 times
3 Answers
1
Just do it like this:
math.floor(num / 1000000) * 1000000
e.g.:
>>> num=1999999
>>> math.floor(num / 1000000) * 1000000
1000000.0
>>> num=2000108
>>> math.floor(num / 1000000) * 1000000
2000000.0

Yuchen
- 30,852
- 26
- 164
- 234
-
1`num = 111; math.floor(num / 1000000) * 1000000` gives `0`, which is not at all what the OP expects (100). – Thierry Lathuille Sep 20 '20 at 19:06
0
To round down positive integer to first digit
from math import floor
def r(n):
gr = 10 ** (len(str(n))-1)
return floor(n / gr) * gr
for i in [199_999, 200_100, 2_100, 315]:
print(r(i))
Output
100000
200000
2000
300

Michael Szczesny
- 4,911
- 5
- 15
- 32
0
def floor_integer(num):
l = str(num)
return int(l[0]) * pow(10, len(l) - 1)
I think that will fits your needs.
print(floor_integer(5))
# 5
print(floor_integer(133))
# 100
print(floor_integer(1543))
# 1000
print(floor_integer(488765))
# 400000
print(floor_integer(1999999))
# 1000000
print(floor_integer(2000108))
# 2000000

franzu
- 49
- 6