RDHDecimalNumberOperations 2.0.2

RDHDecimalNumberOperations 2.0.2

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Feb 2016
SPMSupports SPM

Maintained by Rich Hodgkins.



RDHDecimalNumberOperations

  • Complete test suite
  • All basic operators supported
  • Comparison operators
  • Overflow operators
  • Creation from String
  • abs(), isNaN() methods added for convenience
  • minusOne class var added for convenience
  • Rounding operator

Installation

With cocoapods (using the beta Swift version):

pod 'RDHDecimalNumberOperations', '2.0.0'

Carthage is also supported.

Or, just drop RDHDecimalNumberOperations.swift into your project.

Operators

All the standard operators are supported (see Overflow for the new Swift operators):

  • +
  • -
  • *
  • /
  • +=
  • -=
  • *=
  • /=
  • ++ (as both prefix and suffix)
  • -- (as both prefix and suffix)
  • ==
  • !=
  • >
  • >=
  • <
  • <=

Also the raise to power operator

  • ** - raise a NSDecimalNumber to an Int power
  • **= - raise the NSDecimalNumber to an Int power in place

The unary versions of both + and - work correctly:

let two = NSDecimalNumber(string: "2")
let minusTwo = -two

Overflow

Introduced in Swift were also overflow operators, and these are also supported to prevent any exceptions being thrown with overflow, underflow, loss of precision and the more common dividing by zero.

  • &+
  • &-
  • &*
  • &/
  • &** (with an Int power)

This means the following will not throw an exception, instead returning NSDecimalNumber.notANumber():

let notANumber = NSDecimalNumber.one() / NSDecimalNumber.zero()

Convenience

As well as operator support, a convenience method for obtaining NSDecimalNumbers from Strings has been added.

let numberFromString = "1".decimalValue

And don’t forget you can already utilise IntegerLiteralConvertible (inherited from NSNumber):

let numberFromInt: NSDecimalNumber = 10

Rounding

A rounding method has been added to the NSRoundingMode enum:

let twoThirds = NSDecimalNumber(string: "2") / NSDecimalNumber(string: "3")
let roundedNumber = NSRoundingMode.RoundUp.round(twoThirds, scale: 0)
println("\(twoThirds) rounded up to \(roundedNumber)")

Also for even quicker and easier rounding an operator has been added ~:

let twoThirds = NSDecimalNumber(string: "2") / NSDecimalNumber(string: "3")
let roundedNumber = twoThirds ~ (roundingMode: NSRoundingMode.RoundUp, scale: 0)
println("\(twoThirds) rounded up to \(roundedNumber)")

And for in place rounding:

let twoThirds = NSDecimalNumber(string: "2") / NSDecimalNumber(string: "3")
var roundedNumber = twoThirds
roundedNumber ~= (NSRoundingMode.RoundUp, 0)
println("\(twoThirds) rounded up to \(roundedNumber)")

Output:

0.6666 rounded up to 1