- Complete test suite
- All basic operators supported
- Comparison operators
- Overflow operators
- Creation from
String
abs()
,isNaN()
methods added for convenienceminusOne
classvar
added for convenience- Rounding operator
With Carthage:
github "rhodgkins/RDHDecimalNumberOperations" ~> 2.0
With CocoaPods:
pod 'RDHDecimalNumberOperations', '~> 2.0.0'
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 aNSDecimalNumber
to anInt
power**=
- raise theNSDecimalNumber
to anInt
power in place
The 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 anInt
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