user4909608
user4909608

Reputation:

Rounding INT to make it 0 decimal places

I am running the following code with a round function.

let percentage = round((progress / maxValue) * 100)

However it keeps returning numbers like: 15.0, 25.0, 35.0 etc.

I want it to return: 15, 25, 35, basically 0 decimal places.

How can I do this?

Cheers! :D

Upvotes: 0

Views: 769

Answers (3)

Martin R
Martin R

Reputation: 539935

round() returns a floating point number. You can convert the result to an Int, or call lrint instead:

let percentage = lrint((progress / maxValue) * 100)

The functions

public func lrintf(_: Float) -> Int
public func lrint(_: Double) -> Int

return the integral value nearest to their argument as an integer.

Upvotes: 0

DrummerB
DrummerB

Reputation: 40211

That's because round() returns a floating point number, not an integer:

enter image description here

If you want an integer, you have to convert it:

let percentage = Int(round((progress / maxValue) * 100))

Upvotes: 2

Nathan Mattes
Nathan Mattes

Reputation: 339

Cast it to an Int:

let percentage = round((progress / maxValue) * 100)
let percentageInt = Int(percentage)

Upvotes: 1

Related Questions