Reputation: 4842
I am new to Python and I'm trying to round up a number to 10000
scale.
For example:
a = 154795
b = a / 10000 # 15.4795
c = round(b) # 15
I want to round c
to 16
, even if b = 15.0001
, or round a
to 160000
before passing it to b
.
How would I be able to achieve this?
Thank you for your suggestions.
Upvotes: 1
Views: 1152
Reputation: 67743
The standard integer arithmetic way to round up a positive integer N
divided by D
(emphasis on up, and positive) is
(N + D - 1) // D
The new numerator term is the largest value that won't roll over to the next multiple of the divisor D
, which means we can use integral floor division. For example
def nquot(n, d):
# next quotient (I couldn't think of a better name)
return (n + d - 1) // d
>>> nquot(150000, 10000)
15
>>> nquot(150001, 10000)
16
It's often easier to allow the conversion to floating-point and do the rounding there, as with math.ceil
in the other answers.
PS. your digit grouping is weird. Both a,bbb,ccc
and a.bbb.ccc
are familiar, but a.bbbc
is not.
Upvotes: 2
Reputation: 12002
you should use the ceil
function from the math
module in python
math.ceil() function returns the smallest integral value greater than the number. If number is already integer, same number is returned.
from math import ceil
a = 154795
b = a / 10000 # 15,4795
c = ceil(b) # 16
print(c)
Upvotes: 2
Reputation: 18367
You can use math
's function ceil
.
Here is an example:
import math
a = 150001
b = a / 10000
print(math.ceil(b))
Output:
16
Of course if you want the variable to be stored then you can use:
import math
a = 15001
b = math.ceil(a / 1000)
print(b)
For the same output:
16
Upvotes: 4
Reputation: 78
What @Dschoni said.
import numpy as np
a = 154795
b = a / 10000 # 15,4795
c = np.ceil(b) # always rounds up. Gives 16 here
Upvotes: 1