golang - ceil function like php?
The line
d := float64(length / pagesize)
transforms to float the result of the division. Since the division itself is integer division, it results in 4, so d = 4.0 and math.Ceil(d)
is 4.
Replace the line with
d := float64(length) / float64(pagesize)
and you'll have d=4.3
and int(math.Ceil(d))=5
.
Convert length and pagesize to floats before the division:
d := float64(length) / float64(pagesize)
http://play.golang.org/p/FKWeIj7of5
Avoiding floating point operations (for performance and clarity):
x, y := length, pagesize
q := (x + y - 1) / y;
for x >= 0
and y > 0
.
Or to avoid overflow of x+y
:
q := 1 + (x - 1) / y
It's the same as the C++ version: Fast ceiling of an integer division in C / C++