TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Feb 2016 |
SPMSupports SPM | ✗ |
Maintained by Rich Hodgkins.
String
abs()
, isNaN()
methods added for convenienceminusOne
class var
added for convenienceWith cocoapods (using the beta Swift version):
pod 'RDHDecimalNumberOperations', '2.0.0'
Carthage is also supported.
Or, just drop RDHDecimalNumberOperations.swift
into your project.
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 placeThe unary versions of both +
and -
work correctly:
let two = NSDecimalNumber(string: "2")
let minusTwo = -two
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()
As well as operator support, a convenience method for obtaining NSDecimalNumber
s from String
s has been added.
let numberFromString = "1".decimalValue
And don’t forget you can already utilise IntegerLiteralConvertible
(inherited from NSNumber
):
let numberFromInt: NSDecimalNumber = 10
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