Rounding Float to two decimal places

I have a float value that detriments by 1.0, but the output can be 59.999, or 69.99998 at times and so I don't get round numbers like 60, 70, 80...

I have a workaround, but I would like to know if there is a more elegant way:

    func setYield(total: Float) {
        
        let currentYieldExample = 10
        var totalYield = currentYieldExample + totalYield
        let numberOfPlaces = 2.0
        let multiplier = pow(10.0, numberOfPlaces)
        let rounded = round(Double(totalYield) * multiplier) / multiplier
        
        print("\(Int(rounded * 100))%")
    }

I got the workaround from https://stackoverflow.com/questions/26350977/how-to-round-a-double-to-the-nearest-int-in-swift, but fitting it into my existing code is a little sloppy.

NumberFormatter is something perfect for that kind of thing!

import Foundation

var formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
let value = 59.999
if let formattedString = formatter.string(for: value) {
    print(formattedString, "%")
}
1 Like

Many thanks, NumberFormatter was key!

I ended up with the following code:

import Foundation

var formatter = NumberFormatter()
formatter.maximumFractionDigits = 0
formatter.minimumFractionDigits = 0
formatter.numberStyle = .percent

let value = 59.999
if let formattedString = formatter.string(for: value) {
    print(formattedString)
}

//outputs: "60%"

Thanks for the help!

1 Like
Terms of Service

Privacy Policy

Cookie Policy