0

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.

Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • 2
    Possible duplicate of [Easiest way to truncate float to 2 decimal places?](http://stackoverflow.com/questions/27827742/easiest-way-to-truncate-float-to-2-decimal-places) – Eric Aya Dec 01 '15 at 14:22
  • @EricD. unfortunalty this solution do not handle condition for the nearest tenth rounding of quarter rounding. – Oleg Gordiichuk Dec 01 '15 at 14:26
  • First range (0.25-0.025..0.25 + 0.015), second (0.3-0.035..0.3+0.05). What is a law for this rounding? – MBo Dec 01 '15 at 14:36
  • It should round value to the nearest tenth or the nearest quarter. For example (x.00-x.05) = x.00 (x.265-x.350) = x.30 (x.730-x.765) = x.75 – Oleg Gordiichuk Dec 01 '15 at 14:39

3 Answers3

2

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
R Menke
  • 8,183
  • 4
  • 35
  • 63
1
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
user3441734
  • 16,722
  • 2
  • 40
  • 59
1

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
    }
}
Sethmr
  • 3,046
  • 1
  • 24
  • 42