Skip to content

Use NSDecimalString(_:_) for Decimal -> String conversion. #2396

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 68 additions & 57 deletions Foundation/Decimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -267,61 +267,9 @@ extension Decimal : CustomStringConvertible {
self = theDecimal
}

// Note: In the Darwin overlay, `description` is implemented in terms of
// `NSDecimalString(_:_:)`; here, it's the other way around.
public var description: String {
if self.isNaN {
return "NaN"
}
if _length == 0 {
return "0"
}
var copy = self
let ZERO: CChar = 0x30 // ASCII '0' == 0x30
let DECIMALPOINT: CChar = 0x2e // ASCII '.' == 0x2e
let MINUS: CChar = 0x2d // ASCII '-' == 0x2d

let bufferSize = 200 // Max value: 39 + 128 + sign + decimal point
var buffer = Array<CChar>(repeating: 0, count: bufferSize)

var i = bufferSize - 1
while copy._exponent > 0 {
i -= 1
buffer[i] = ZERO
copy._exponent -= 1
}

if copy._exponent == 0 {
copy._exponent = 1
}

while copy._length != 0 {
var remainder: UInt16 = 0
if copy._exponent == 0 {
i -= 1
buffer[i] = DECIMALPOINT
}
copy._exponent += 1
(remainder, _) = divideByShort(&copy, 10)
i -= 1
buffer[i] = Int8(remainder) + ZERO
}
if copy._exponent <= 0 {
while copy._exponent != 0 {
i -= 1
buffer[i] = ZERO
copy._exponent += 1
}
i -= 1
buffer[i] = DECIMALPOINT
i -= 1
buffer[i] = ZERO
}
if copy._isNegative != 0 {
i -= 1
buffer[i] = MINUS
}
return String(cString: Array(buffer.suffix(from: i)))
var value = self
return NSDecimalString(&value, nil)
}
}

Expand Down Expand Up @@ -1691,10 +1639,73 @@ public func NSDecimalMultiplyByPowerOf10(_ result: UnsafeMutablePointer<Decimal>
}

public func NSDecimalString(_ dcm: UnsafePointer<Decimal>, _ locale: Any?) -> String {
guard locale == nil else {
fatalError("Locale not supported: \(locale!)")

var copy = dcm.pointee
if copy.isNaN {
return "NaN"
}
if copy._length == 0 {
return "0"
}

let ZERO: CChar = 0x30 // ASCII '0' == 0x30
let DECIMALPOINT: CChar = 0x2e // ASCII '.' == 0x2e
let MINUS: CChar = 0x2d // ASCII '-' == 0x2d
let bufferSize = 200 // Max value: 39 + 128 + sign + decimal point
var buffer = Array<CChar>(repeating: 0, count: bufferSize)

var i = bufferSize - 1
while copy._exponent > 0 {
i -= 1
buffer[i] = ZERO
copy._exponent -= 1
}

if copy._exponent == 0 {
copy._exponent = 1
}
return dcm.pointee.description

while copy._length != 0 {
var remainder: UInt16 = 0
if copy._exponent == 0 {
i -= 1
buffer[i] = DECIMALPOINT
}
copy._exponent += 1
(remainder, _) = divideByShort(&copy, 10)
i -= 1
buffer[i] = Int8(remainder) + ZERO
}
if copy._exponent <= 0 {
while copy._exponent != 0 {
i -= 1
buffer[i] = ZERO
copy._exponent += 1
}
i -= 1
buffer[i] = DECIMALPOINT
i -= 1
buffer[i] = ZERO
}
if copy._isNegative != 0 {
i -= 1
buffer[i] = MINUS
}
let result = String(cString: Array(buffer.suffix(from: i)))

var decimalSeparator: String?
if let locale = locale as? Locale {
decimalSeparator = locale.decimalSeparator
} else if let dictionary = locale as? [NSLocale.Key: String] {
decimalSeparator = dictionary[NSLocale.Key.decimalSeparator]
} else if let dictionary = locale as? [String: String] {
decimalSeparator = dictionary[NSLocale.Key.decimalSeparator.rawValue]
}

if let dcm = decimalSeparator, dcm != "." {
return result.replacingOccurrences(of: ".", with: dcm)
}
return result
}

private func multiplyBy10(_ dcm: inout Decimal, andAdd extra:Int) -> NSDecimalNumber.CalculationError {
Expand Down
9 changes: 4 additions & 5 deletions Foundation/NSDecimalNumber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -206,14 +206,13 @@ open class NSDecimalNumber : NSNumber {
}

open override var description: String {
return self.decimal.description
var number = self.decimal
return NSDecimalString(&number, nil)
}

open override func description(withLocale locale: Locale?) -> String {
guard locale == nil else {
fatalError("Locale not supported: \(locale!)")
}
return self.decimal.description
var number = self.decimal
return NSDecimalString(&number, locale)
}

open class var zero: NSDecimalNumber {
Expand Down
119 changes: 88 additions & 31 deletions TestFoundation/TestDecimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,6 @@

class TestDecimal: XCTestCase {

static var allTests : [(String, (TestDecimal) -> () throws -> Void)] {
return [
("test_NSDecimalNumberInit", test_NSDecimalNumberInit),
("test_AdditionWithNormalization", test_AdditionWithNormalization),
("test_BasicConstruction", test_BasicConstruction),
("test_Constants", test_Constants),
("test_Description", test_Description),
("test_ExplicitConstruction", test_ExplicitConstruction),
("test_Maths", test_Maths),
("test_Misc", test_Misc),
("test_MultiplicationOverflow", test_MultiplicationOverflow),
("test_NaNInput", test_NaNInput),
("test_NegativeAndZeroMultiplication", test_NegativeAndZeroMultiplication),
("test_Normalise", test_Normalise),
("test_NSDecimal", test_NSDecimal),
("test_PositivePowers", test_PositivePowers),
("test_RepeatingDivision", test_RepeatingDivision),
("test_Round", test_Round),
("test_ScanDecimal", test_ScanDecimal),
("test_SimpleMultiplication", test_SimpleMultiplication),
("test_SmallerNumbers", test_SmallerNumbers),
("test_ZeroPower", test_ZeroPower),
("test_doubleValue", test_doubleValue),
("test_NSDecimalNumberValues", test_NSDecimalNumberValues),
("test_bridging", test_bridging),
("test_stringWithLocale", test_stringWithLocale),
]
}

func test_NSDecimalNumberInit() {
XCTAssertEqual(NSDecimalNumber(mantissa: 123456789000, exponent: -2, isNegative: true), -1234567890)
XCTAssertEqual(NSDecimalNumber(decimal: Decimal()).decimalValue, Decimal(0))
Expand Down Expand Up @@ -203,8 +174,43 @@ class TestDecimal: XCTestCase {
XCTAssertEqual("-5", Decimal(signOf: Decimal(-3), magnitudeOf: Decimal(5)).description)
XCTAssertEqual("5", Decimal(signOf: Decimal(3), magnitudeOf: Decimal(-5)).description)
XCTAssertEqual("-5", Decimal(signOf: Decimal(-3), magnitudeOf: Decimal(-5)).description)
XCTAssertEqual("5", NSDecimalNumber(decimal:Decimal(5)).description)
XCTAssertEqual("-5", NSDecimalNumber(decimal:Decimal(-5)).description)
XCTAssertEqual("5", NSDecimalNumber(decimal: Decimal(5)).description)
XCTAssertEqual("-5", NSDecimalNumber(decimal: Decimal(-5)).description)
XCTAssertEqual("-3402823669209384634633746074317682114550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", Decimal.leastFiniteMagnitude.description)
XCTAssertEqual("3402823669209384634633746074317682114550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", Decimal.greatestFiniteMagnitude.description)
XCTAssertEqual("0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", Decimal.leastNormalMagnitude.description)
XCTAssertEqual("0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", Decimal.leastNonzeroMagnitude.description)

let fr = Locale(identifier: "fr_FR")
let leastFiniteMagnitude = "-3402823669209384634633746074317682114550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
let greatestFiniteMagnitude = "3402823669209384634633746074317682114550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

XCTAssertEqual("0", NSDecimalNumber(decimal: Decimal()).description(withLocale: fr))
XCTAssertEqual("1000", NSDecimalNumber(decimal: Decimal(1000)).description(withLocale: fr))
XCTAssertEqual("10", NSDecimalNumber(decimal: Decimal(10)).description(withLocale: fr))
XCTAssertEqual("123,458", NSDecimalNumber(decimal: Decimal(123.458)).description(withLocale: fr))
XCTAssertEqual("123", NSDecimalNumber(decimal: Decimal(UInt8(123))).description(withLocale: fr))
XCTAssertEqual("3,14159265358979323846264338327950288419", NSDecimalNumber(decimal: Decimal.pi).description(withLocale: fr))
XCTAssertEqual("-30000000000", NSDecimalNumber(decimal: Decimal(sign: .minus, exponent: 10, significand: Decimal(3))).description(withLocale: fr))
XCTAssertEqual("123456,789", NSDecimalNumber(decimal: Decimal(string: "123456.789")!).description(withLocale: fr))
XCTAssertEqual(leastFiniteMagnitude, NSDecimalNumber(decimal: Decimal.leastFiniteMagnitude).description(withLocale: fr))
XCTAssertEqual(greatestFiniteMagnitude, NSDecimalNumber(decimal: Decimal.greatestFiniteMagnitude).description(withLocale: fr))
XCTAssertEqual("0,0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", NSDecimalNumber(decimal: Decimal.leastNormalMagnitude).description(withLocale: fr))
XCTAssertEqual("0,0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", NSDecimalNumber(decimal: Decimal.leastNonzeroMagnitude).description(withLocale: fr))

let en = Locale(identifier: "en_GB")
XCTAssertEqual("0", NSDecimalNumber(decimal: Decimal()).description(withLocale: en))
XCTAssertEqual("1000", NSDecimalNumber(decimal: Decimal(1000)).description(withLocale: en))
XCTAssertEqual("10", NSDecimalNumber(decimal: Decimal(10)).description(withLocale: en))
XCTAssertEqual("123.458", NSDecimalNumber(decimal: Decimal(123.458)).description(withLocale: en))
XCTAssertEqual("123", NSDecimalNumber(decimal: Decimal(UInt8(123))).description(withLocale: en))
XCTAssertEqual("3.14159265358979323846264338327950288419", NSDecimalNumber(decimal: Decimal.pi).description(withLocale: en))
XCTAssertEqual("-30000000000", NSDecimalNumber(decimal: Decimal(sign: .minus, exponent: 10, significand: Decimal(3))).description(withLocale: en))
XCTAssertEqual("123456.789", NSDecimalNumber(decimal: Decimal(string: "123456.789")!).description(withLocale: en))
XCTAssertEqual(leastFiniteMagnitude, NSDecimalNumber(decimal: Decimal.leastFiniteMagnitude).description(withLocale: en))
XCTAssertEqual(greatestFiniteMagnitude, NSDecimalNumber(decimal: Decimal.greatestFiniteMagnitude).description(withLocale: en))
XCTAssertEqual("0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", NSDecimalNumber(decimal: Decimal.leastNormalMagnitude).description(withLocale: en))
XCTAssertEqual("0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", NSDecimalNumber(decimal: Decimal.leastNonzeroMagnitude).description(withLocale: en))
}

func test_ExplicitConstruction() {
Expand Down Expand Up @@ -1116,4 +1122,55 @@ class TestDecimal: XCTestCase {
XCTAssertEqual(Decimal(string: s2, locale: en_US)?.description, "1234")
XCTAssertEqual(Decimal(string: s2, locale: fr_FR)?.description, s1)
}

func test_NSDecimalString() {
var decimal = Decimal(string: "-123456.789")!
XCTAssertEqual(NSDecimalString(&decimal, nil), "-123456.789")
let en = NSDecimalString(&decimal, Locale(identifier: "en_GB"))
XCTAssertEqual(en, "-123456.789")
let fr = NSDecimalString(&decimal, Locale(identifier: "fr_FR"))
XCTAssertEqual(fr, "-123456,789")

let d1: [NSLocale.Key: String] = [ .decimalSeparator: "@@@"]
XCTAssertEqual(NSDecimalString(&decimal, d1), "-123456@@@789")
let d2: [NSLocale.Key: String] = [ .decimalSeparator: "()"]
XCTAssertEqual(NSDecimalString(&decimal, NSDictionary(dictionary: d2)), "-123456()789")
let d3: [String: String] = [ "kCFLocaleDecimalSeparatorKey": "X"]
XCTAssertEqual(NSDecimalString(&decimal, NSDictionary(dictionary: d3)), "-123456X789")

// Input is ignored
let d4: [Int: String] = [123: "X"]
XCTAssertEqual(NSDecimalString(&decimal, NSDictionary(dictionary: d4)), "-123456.789")
}


static var allTests : [(String, (TestDecimal) -> () throws -> Void)] {
return [
("test_NSDecimalNumberInit", test_NSDecimalNumberInit),
("test_AdditionWithNormalization", test_AdditionWithNormalization),
("test_BasicConstruction", test_BasicConstruction),
("test_Constants", test_Constants),
("test_Description", test_Description),
("test_ExplicitConstruction", test_ExplicitConstruction),
("test_Maths", test_Maths),
("test_Misc", test_Misc),
("test_MultiplicationOverflow", test_MultiplicationOverflow),
("test_NaNInput", test_NaNInput),
("test_NegativeAndZeroMultiplication", test_NegativeAndZeroMultiplication),
("test_Normalise", test_Normalise),
("test_NSDecimal", test_NSDecimal),
("test_PositivePowers", test_PositivePowers),
("test_RepeatingDivision", test_RepeatingDivision),
("test_Round", test_Round),
("test_ScanDecimal", test_ScanDecimal),
("test_SimpleMultiplication", test_SimpleMultiplication),
("test_SmallerNumbers", test_SmallerNumbers),
("test_ZeroPower", test_ZeroPower),
("test_doubleValue", test_doubleValue),
("test_NSDecimalNumberValues", test_NSDecimalNumberValues),
("test_bridging", test_bridging),
("test_stringWithLocale", test_stringWithLocale),
("test_NSDecimalString", test_NSDecimalString),
]
}
}