Last active
April 23, 2021 13:57
-
-
Save moderateepheezy/35aeb7ab5b2bd010314973ef500e892a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Some numbers can have strange behaviour going back to Double or Float | |
If rounding in Decimal it's best to keep it in Decimal until the point of display or transport in JSON | |
Read here: https://forums.swift.org/t/jsonencoder-encodable-floating-point-rounding-error/41390/6 | |
**/ | |
/* | |
A helper that assists in rounding a Double to a given number of decimal places | |
*/ | |
public func rounded(_ value: Double, places: Int16) -> Decimal { | |
let roundingBehavior = NSDecimalNumberHandler( | |
roundingMode: .bankers, | |
scale: places, | |
raiseOnExactness: true, | |
raiseOnOverflow: true, | |
raiseOnUnderflow: true, | |
raiseOnDivideByZero: true | |
) | |
return NSDecimalNumber(value: value).rounding(accordingToBehavior: roundingBehavior) as Decimal | |
} | |
/* | |
A helper that assists in rounding a Float to a given number of decimal places | |
*/ | |
public func rounded(_ value: Float, places: Int16) -> Decimal { | |
let roundingBehavior = NSDecimalNumberHandler( | |
roundingMode: .bankers, | |
scale: places, | |
raiseOnExactness: true, | |
raiseOnOverflow: true, | |
raiseOnUnderflow: true, | |
raiseOnDivideByZero: true | |
) | |
return NSDecimalNumber(value: value).rounding(accordingToBehavior: roundingBehavior) as Decimal | |
} | |
/// examples | |
func testRoundedToDecimalPlaces_Double() { | |
let amount: Double = 30.5657676754 | |
let roundedTo2dp = rounded(amount, places: 2) | |
let roundedTo4dp = rounded(amount, places: 4) | |
XCTAssertEqual(30.57, roundedTo2dp) | |
XCTAssertEqual(30.5658, roundedTo4dp) | |
} | |
func testRoundedToDecimalPlaces_Float() { | |
let amount: Float = 30.5657676754 | |
let roundedTo2dp = rounded(amount, places: 2) | |
let roundedTo4dp = rounded(amount, places: 4) | |
XCTAssertEqual(30.57, roundedTo2dp) | |
XCTAssertEqual(30.5658, roundedTo4dp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment