Ranjan Ranjan - 1 month ago 6
Swift Question

Swift roundf not working with float value

let amount:Float = 2.235
print("\(roundf(self.amountTax * 100) / 100)")


it returns 2.23

but it should be 2.24

Answer

This problem is persistent for most of the inbuilt function so in my case I have created a function of my own here it is :

func customRound(parm: Float) -> Float {
   // print("\(parm)")
    let strParm = "\(parm)"
    let arrParm = strParm.componentsSeparatedByString(".")
    let lastValue = arrParm.last
    var valueInt = Int(lastValue!)

    //985656556
    //985656556/10 => remainder : 6, divisble : 98565655, next divisible value : 98565656
    //985656596/10 => remainder : 6, divisble : 98565659, next divisible value : 98565660
    //985699996/10 => remainder : 6, divisble : 98569999, next divisible value : 98570000 = 98569999 + 1

    if (valueInt > 0){
        var i = lastValue!.characters.count
        while i > 2
        {
            let divisible = valueInt! / 10
            let remainder = valueInt! % 10

            if(remainder >= 5){
                valueInt = divisible + 1;
            } else {
                valueInt = divisible;
            }
            i -= 1
        }
        let strFinalValue = arrParm.first! + "." + "\(valueInt!)"
        //print(strFinalValue)
        return Float(strFinalValue)!

    }else{
        return parm
    }


}

to show the output do this:

print(“\(self.customRound(amount))”)

I hope it can be of some help.

Thanks