Skip to content

Commit a5a68ca

Browse files
mortenbekditlevsenjrose-apple
authored andcommitted
Fix negation of 0 length Decimal (swiftlang#15986)
A Decimal value with _length 0 and _isNegative set to 1 is interpreted as a NaN. The 'negate()' function however, flipped the _isNegative flag without regard for the _length 0 case. This meant that -0 would become NaN. The fix checks for the _length 0 special case. In NSDecimalSubtract() the same check was performed. Since this now happens in negate(), it is removed from the NSDecimalSubtract() function.
1 parent a46d237 commit a5a68ca

File tree

2 files changed

+4
-0
lines changed

2 files changed

+4
-0
lines changed

stdlib/public/SDK/Foundation/Decimal.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ extension Decimal {
5959
public mutating func formTruncatingRemainder(dividingBy other: Decimal) { fatalError("Decimal does not yet fully adopt FloatingPoint") }
6060

6161
public mutating func negate() {
62+
guard _length != 0 else { return }
6263
_isNegative = _isNegative == 0 ? 1 : 0
6364
}
6465

test/stdlib/TestDecimal.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,9 @@ class TestDecimal : TestDecimalSuper {
272272
expectEqual(.minus, d.sign)
273273
d.negate()
274274
expectEqual(.plus, d.sign)
275+
var e = Decimal(0)
276+
e.negate()
277+
expectEqual(e, 0)
275278
expectTrue(Decimal(3.5).isEqual(to: Decimal(3.5)))
276279
expectTrue(Decimal.nan.isEqual(to: Decimal.nan))
277280
expectTrue(Decimal(1.28).isLess(than: Decimal(2.24)))

0 commit comments

Comments
 (0)