Search code examples
typesjuliafloorceil

Julia: Can ceil/floor return an integer?


Why don't ceil() and floor() return an integer? How can I return an integer?

a = 10
b = 3
typeof(a/b)
  ## Float64

c = ceil(a/b)
typeof(c)
  ## Float64

This issue bothered me in the context of calculating a range, e.g.

k = 0:1:c
  ## 0.0:1.0:4.0
typeof(k)
  ## StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}}

Full disclosure: I think I have an answer, so I'm going to answer my own question, however please do post an answer if you have a better one. Hopefully next time someone looks, they'll find an answer easily here.


Solution

  • At times you want ceil() and floor() to return something other than an integer, e.g. Inf, NaN. However, you can return an integer like this:

    julia> c = ceil(Int64, a/b)
    julia> typeof(c)
    Int64 
    
    julia> k = 0:1:c
    0:1:4
    
    julia> typeof(k)
    StepRange{Int64, Int64}
    

    See the docs