Oleg Gordiichuk Oleg Gordiichuk - 5 months ago 8
Swift Question

Value should be rounded to nearest tenth or the nearest quarter

I need to round number to nearest tenth or the nearest quarter.

For example:

If values are from 0.225 to 0.265, they are round to 0.25 and when they are
from 0.265 to 0.350, they are round to 0.30.

So i need to know what is the nearest rounding is for certain number and than round it.

Answer

You can use a switch statement.

Main func:

func differentRounding(value:Double) -> Double {

    var decimalValue = value % 1
    let intValue = value - decimalValue

    switch decimalValue {
    case 0.225..<0.265 :
        decimalValue = 0.25
    case 0.725..<0.765 :
        decimalValue = 0.75
    default :
        decimalValue = ((decimalValue * 10).roundDownTillFive()) / 10
    }

    return decimalValue + intValue
}

differentRounding(1.2434534545) // 1.25
differentRounding(3.225345346) // 2.25
differentRounding(0.2653453645) // 0.3
differentRounding(0.05) // 0
differentRounding(0.04456456) // 0

Rounding down till 5 extension:

extension Double {
    func roundDownTillFive() -> Double {

        var decimalValue = self % 1
        let intValue = self - decimalValue

        switch decimalValue {
        case 0.0...0.5 :
            decimalValue = 0.0
        case 0.5...1.0 :
            decimalValue = 1.0
        default :
            break
        }

        return decimalValue + intValue
    }
}

Double(0.5).roundDownTillFive() // 0
Double(0.50000001).roundDownTillFive() // 1