29

I want to return the least integer value greater than or equal to integer division. So I used math.ceil, but can not get the value I want.

package main

import (
    "fmt"
    "math"
)

func main() {
    var pagesize int = 10
    var length  int = 43

    d := float64(length / pagesize)
    page := int(math.Ceil(d))

    fmt.Println(page)
    // output 4 not 5
}

http://golang.org/pkg/math/#Ceil

http://play.golang.org/p/asHta1HkO_

What is wrong? Thanks.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
leiyonglin
  • 6,474
  • 12
  • 36
  • 41

4 Answers4

59

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.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
14

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++

Jendas
  • 3,359
  • 3
  • 27
  • 55
  • Worth noting that (at least on my 2014 MacBook Pro with a 2.5GHz i7) this is only about 17% faster than the `float64` / `math.Ceil` solution, and only with 32-bit integers—with `int64` it's about 24% slower. [Benchmark here](https://play.golang.org/p/75ybV6Efe0z)—although it doesn't actually work in the Go playground, I think b/c it doesn't have sufficient time resolution. Still using this answer in my code for clarity, though. – David Moles Feb 13 '19 at 19:05
13

Convert length and pagesize to floats before the division:

d := float64(length) / float64(pagesize)

http://play.golang.org/p/FKWeIj7of5

lnmx
  • 10,846
  • 3
  • 40
  • 36
4

You can check the remainder to see if it should be raised to the next integer.

page := length / pagesize
if length % pagesize > 0 {
    page++
}
Matt Bajorek
  • 189
  • 2
  • 5