iOS - Swift NSNumber 数字

时间:2022-04-21 21:50:28

前言

	public class NSNumber : NSValue
public class NSDecimalNumber : NSNumber
  • NSNumber 可以被赋值为各种数值类型。我们可以将一个 Int 类型的值直接传递给一个需要 NSNumber 类型参数或变量,Swift 会自动转换,如果两者类型不一致,会强制类型转换。

  • 从 NSNumber 赋值给 Swift 数值类型是,数值类型会根据会更具声明类型将 NSNumber 强制转换。

1、Swift 数字类型 与 NSNumber 类型 的相互转换

	// Swift 数字 转 NSNumber

		let nsNum1:NSNumber = 1

		let nsNum2 = NSNumber(integer: 1)
let nsNum3 = NSNumber(unsignedInteger: 1)
let nsNum4 = NSNumber(float: 1.1)
let nsNum5 = NSNumber(double: 3.2)
let nsNum6 = NSNumber(bool: true) // NSNumber 转 Swift 数字 let num1 = nsNum1.integerValue
let num2 = nsNum2.unsignedIntegerValue
let num3 = nsNum3.floatValue
let num4 = nsNum4.doubleValue
let num5 = nsNum5.boolValue

2、比较两个 NSNumber 类型数据的大小

	let nsNum1:NSNumber = 10
let nsNum2:NSNumber = 10.1 // 判断两个值是否相等
let bl:Bool = nsNum1.isEqualToNumber(nsNum2) // 判断两个值的大小
let result:NSComparisonResult = nsNum1.compare(nsNum2)

3、NSNumber 与 String 的相互转换

	// NSNumber 转换 NSString
let str:String = NSNumber(float: 10.456).stringValue // NSString 转 NSNumber
let nsNum:NSNumber = NSNumber(float: NSString(string: str).floatValue)

4、加、减、乘、除、n次方

	let dcNun1 = NSDecimalNumber(string:"15.99")
let dcNun2 = NSDecimalNumber(string:"29.99")
let dcNun3 = NSDecimalNumber(string:"5.00")
let dcNun4 = NSDecimalNumber(string:".90")
let dcNun5 = NSDecimalNumber(string:"2.0") // 加 Adding
let subtotal = dcNun1.decimalNumberByAdding(dcNun2) // 减 Subtracting
let afterCoupon = subtotal.decimalNumberBySubtracting(dcNun3) // 乘 Multiplying
let afterDiscount = afterCoupon.decimalNumberByMultiplyingBy(dcNun4) // 平均 Dividing
let average = afterDiscount.decimalNumberByDividingBy(dcNun5) // n 次方 RaisingToPower
let averageSquared = average.decimalNumberByRaisingToPower(2)

5、四舍五入 运算

	/*
enum NSRoundingMode : UInt { case RoundPlain // Round up on a tie 貌似取整
case RoundDown // Always down == truncate 只舍不入
case RoundUp // Always up 只入不舍
case RoundBankers // on a tie round so last digit is even 貌似四舍五入
}
*/ // 90.7049 + 0.22 然后四舍五入 let roundUp = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundBankers,
scale: 2,
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: true) let subtotal = NSDecimalNumber(string:"90.7049")
let discount = NSDecimalNumber(string:"0.22") // 加 保留 2 位小数
let total = subtotal.decimalNumberByAdding(discount, withBehavior: roundUp)