Skip to content
This repository has been archived by the owner on Mar 29, 2018. It is now read-only.

Commit

Permalink
Merge pull request #68 from michaeleisel/round_to_nearest
Browse files Browse the repository at this point in the history
Round to nearest
  • Loading branch information
pNre committed Feb 2, 2015
2 parents 474f923 + d1771b1 commit c660a68
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
11 changes: 11 additions & 0 deletions ExSwift/Double.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,16 @@ public extension Double {
let rand = Double(arc4random() % (UInt32(RAND_MAX) + 1))
return ((rand / Double(RAND_MAX)) * diff) + min;
}

/**
Just like round(), except it supports rounding to an arbitrary number, not just 1
Be careful about rounding errors

:params: increment the increment to round to
*/
func roundToNearest(increment: Double) -> Double {
let remainder = self % increment
return remainder < increment / 2 ? self - remainder : self - remainder + increment
}

}
9 changes: 8 additions & 1 deletion ExSwiftTests/ExSwiftDoubleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,12 @@ class ExSwiftDoubleTests: XCTestCase {

func testRandom() {
}


func testRoundToNearest () {
XCTAssertEqualWithAccuracy(2.5.roundToNearest(0.3), 2.4, 0.01)
XCTAssertEqualWithAccuracy(0.roundToNearest(0.3), 0.0, 0.01)
XCTAssertEqualWithAccuracy(4.0.roundToNearest(2), 4.0, 0.01)
XCTAssertEqualWithAccuracy(10.0.roundToNearest(3), 9.0, 0.01)
XCTAssertEqualWithAccuracy(-2.0.roundToNearest(3), -3.0, 0.01)
}
}

0 comments on commit c660a68

Please sign in to comment.