Swift 版本,也有获取美元金额的奖励功能。
extension NSDecimalNumber {
/// Returns the dollars only, suitable for printing. Chops the cents.
func dollarsOnlyString() -> String {
let behaviour = NSDecimalNumberHandler(roundingMode:.RoundDown,
scale: 0, raiseOnExactness: false,
raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let rounded = decimalNumberByRoundingAccordingToBehavior(behaviour)
let formatter = NSNumberFormatter()
formatter.numberStyle = .NoStyle
let str = formatter.stringFromNumber(rounded)
return str ?? "0"
}
/// Returns the cents only, e.g. "00" for no cents.
func centsOnlyString() -> String {
let behaviour = NSDecimalNumberHandler(roundingMode:.RoundDown,
scale: 0, raiseOnExactness: false,
raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let rounded = decimalNumberByRoundingAccordingToBehavior(behaviour)
let centsOnly = decimalNumberBySubtracting(rounded)
let centsAsWholeNumber = centsOnly.decimalNumberByMultiplyingByPowerOf10(2)
let formatter = NSNumberFormatter()
formatter.numberStyle = .NoStyle
formatter.formatWidth = 2
formatter.paddingCharacter = "0"
let str = formatter.stringFromNumber(centsAsWholeNumber)
return str ?? "00"
}
}
测试:
class NSDecimalNumberTests: XCTestCase {
func testDollarsBreakdown() {
var amount = NSDecimalNumber(mantissa: 12345, exponent: -2, isNegative: false)
XCTAssertEqual(amount.dollarsOnlyString(), "123")
XCTAssertEqual(amount.centsOnlyString(), "45")
// Check doesn't round dollars up.
amount = NSDecimalNumber(mantissa: 12365, exponent: -2, isNegative: false)
XCTAssertEqual(amount.dollarsOnlyString(), "123")
XCTAssertEqual(amount.centsOnlyString(), "65")
// Check zeros
amount = NSDecimalNumber(mantissa: 0, exponent: 0, isNegative: false)
XCTAssertEqual(amount.dollarsOnlyString(), "0")
XCTAssertEqual(amount.centsOnlyString(), "00")
// Check padding
amount = NSDecimalNumber(mantissa: 102, exponent: -2, isNegative: false)
XCTAssertEqual(amount.dollarsOnlyString(), "1")
XCTAssertEqual(amount.centsOnlyString(), "02")
}
}