Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

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.

Upvotes: 0

Views: 491

Answers (3)

Sethmr
Sethmr

Reputation: 3084

Here is an extension to double to round to the nearest double amount rounding up for any value that is equal to the input divided by 2.

extension Double {
    func roundToNearestValue(value: Double) -> Double {
        let remainder = self % value
        let shouldRoundUp = remainder >= value/2 ? true : false
        let multiple = floor(self / value)
        let returnValue = !shouldRoundUp ? value * multiple : value * multiple + value
        return returnValue
    }
}

Upvotes: 1

R Menke
R Menke

Reputation: 8401

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

Upvotes: 2

user3441734
user3441734

Reputation: 17572

import Foundation

func specround(d: Double)->Double {
    let d1 = round(d * 10) / 10
    let d2 = round(d * 4 ) / 4

    return abs(d2-d) < abs(d1-d) ? d2 : d1
}

specround(1.2249999) // 1.2
specround(1.225)     // 1.25
specround(1.276)     // 1.3

Upvotes: 1

Related Questions