How do you round floats to ints?

hey Chris! I want to know how to change floats to ints and was wondering if you could please help me with that? the way i was taught it was using “roundedValue” but I’m guessing that was a part of an old update and I’m not sure how to do it anymore.

I’m sorry I know I keep on asking silly questions but I just don’t have much swiftui experience:/

Wouldn’t changing the underscore to “roundedValue” do the trick? I’m not sure that it wouldn’t be truncated, rather than rounded, so you might have to add 0.5 to self.sliderValue.

1 Like

Yeah, Int(floatValue) will truncate the float, not round it.

Depending on how you want to round your float, you can use rounded(_:), like so:

let f: Float = 123.45
print(Int(f.rounded()))
//123
print(Int(f.rounded(.awayFromZero)))
//124
print(Int(f.rounded(.towardZero)))
//123
print(Int(f.rounded(.down)))
//123
print(Int(f.rounded(.up)))
//124
print(Int(f.rounded(.toNearestOrEven)))
//123
print(Int(f.rounded(.toNearestOrAwayFromZero)))
//123

See here for the docs on the various rules.

2 Likes

The simplest way I know to round a number to an integer is

intValue = Int(floatValue + 0.5)

But this only works if you know that floatValue is not negative.

1 Like