Mathias Mathias - 3 years ago 156
Swift Question

Not displaying decimals with Swift

I want to display the value of a slider into a label. The label is called rate and the slider is sliderrate, I tried this:

@IBAction func sliderValueChanged(_ sender: UISlider) {
rate.text = String(round(sliderrate.value))
}


As you can see I tried to round it in order to not display the decimals, but it's not working, I still have one decimal. Can someone help me please

Answer Source

Swift's rounding functions return the same type as you put into them. So if you round a Double, what you get back is still a Double. To display the rounded number as an integer, convert it to an Int first:

Int(slidernote.value.rounded())

Alternately, you can use the lround function from the standard C library, which returns an Int:

import Foundation

lround(slidernote.value)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download