Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
NSDecimalNumber Additions for Swift
import Foundation
// MARK: - Comparable
extension NSDecimalNumber: Comparable {}
public func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .OrderedSame
}
public func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
// MARK: - Arithmetic Operators
public prefix func -(value: NSDecimalNumber) -> NSDecimalNumber {
return value.decimalNumberByMultiplyingBy(NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true))
}
public func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.decimalNumberByAdding(rhs)
}
public func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.decimalNumberBySubtracting(rhs)
}
public func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.decimalNumberByMultiplyingBy(rhs)
}
public func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.decimalNumberByDividingBy(rhs)
}
public func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber {
return lhs.decimalNumberByRaisingToPower(rhs)
}

Simple question: may I use these in my SwiftAdditions framework?

ptrocki commented Apr 26, 2017

For swift 3

import Foundation

// MARK: - Comparable

extension NSDecimalNumber: Comparable {}

public func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
  return lhs.compare(rhs) == .orderedSame
}

public func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
  return lhs.compare(rhs) == .orderedAscending
}

// MARK: - Arithmetic Operators

public prefix func -(value: NSDecimalNumber) -> NSDecimalNumber {
  return value.multiplying(by: NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true))
}

public func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
  return lhs.adding(rhs)
}

public func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
  return lhs.subtracting(rhs)
}

public func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
  return lhs.multiplying(by: rhs)
}

public func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
  return lhs.dividing(by: rhs)
}

public func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber {
  return lhs.raising(toPower: rhs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment