DEV Community

Cover image for Casting Integers to Doubles
acodeguy
acodeguy

Posted on

Casting Integers to Doubles

This week I got tripped-up by what I reckon is a rookie mistake.

Let's say we're building a clock face with just the hours. We'd use a maximum of 12 to represent each hour. 3 would point to 3 on the clock face, 7 to 7, etc

I was trying to work out how many degrees of a circular gauge view to fill when given two Integers representing its current and maximum possible values.

What I did wrong

let current: Int = 6 // where the hour hand should point to...
let max: Int = 12
let degreesToFill: Double = Double(current / max) * 360.0
Enter fullscreen mode Exit fullscreen mode

How I fixed it:

let degreesToFill: Double = (Double(current) / Double(max)) * 360.0
Enter fullscreen mode Exit fullscreen mode

The mistake:

It seems that attempting to cast the result of the initial division returns 0 rather than the result as a Double, as expected.

The way which worked was to cast each Integer separately, then divide them before multiplying by the maximum number of degrees in the circle.

Top comments (0)