Skip to content

Commit 93c31fd

Browse files
committed
Fix CGFloat.rounded(by displayScale) for a floating point error
Where a value is -0.16666666666674246, -0.0 is the rounded value to be expected. However the current implementation returned -0.3333333333333. This is because the floating point error. So this patch truncates it.
1 parent 461f637 commit 93c31fd

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

Sources/Extensions.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@ import UIKit
77
extension CGFloat {
88
/// Returns this value rounded to an logical pixel value by a display scale
99
func rounded(by displayScale: CGFloat) -> CGFloat {
10-
return (self * displayScale).rounded(.toNearestOrAwayFromZero) / displayScale
10+
let p = 1.0e9
11+
let v = (self * p).rounded(.towardZero) / p
12+
return (v * displayScale).rounded(.toNearestOrAwayFromZero) / displayScale
1113
}
1214
func isEqual(to: CGFloat, on displayScale: CGFloat) -> Bool {
1315
return rounded(by: displayScale) == to.rounded(by: displayScale)

Tests/ExtensionTests.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,20 @@ class ExtensionTests: XCTestCase {
99
XCTAssertNotEqual(CGFloat(333.5).rounded(by: 3), 333.66666666666674)
1010
XCTAssertTrue(CGFloat(333.5).isEqual(to: 333.66666666666674, on: 3.0))
1111
}
12+
13+
func test_roundedByDisplayScale_2() {
14+
XCTAssertEqual(CGFloat(-0.16666666666674246).rounded(by: 3), 0.0)
15+
XCTAssertEqual(CGFloat(0.16666666666674246).rounded(by: 3), 0.0)
16+
17+
XCTAssertEqual(CGFloat(-0.3333333333374246).rounded(by: 3), -0.3333333333333333)
18+
XCTAssertEqual(CGFloat(-0.3333333333074246).rounded(by: 3), -0.3333333333333333)
19+
XCTAssertEqual(CGFloat(0.33333333333374246).rounded(by: 3), 0.3333333333333333)
20+
XCTAssertEqual(CGFloat(0.33333333333074246).rounded(by: 3), 0.3333333333333333)
21+
22+
XCTAssertEqual(CGFloat(-0.16666666666674246).rounded(by: 2), 0.0)
23+
XCTAssertEqual(CGFloat(0.16666666666674246).rounded(by: 2), 0.0)
24+
25+
XCTAssertEqual(CGFloat(-0.16666666666674246).rounded(by: 6), -0.16666666666666666)
26+
XCTAssertEqual(CGFloat(0.16666666666674246).rounded(by: 6), 0.16666666666666666)
27+
}
1228
}

0 commit comments

Comments
 (0)