首先是数字检测 正则表达式 小数点前面三位,小数点后允许两位
Swift
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let expression = "^\\d{0,3}(\\.\\d{0,2})?$"
let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
return numberOfMatches != 0
}
然后货币交易以及向上取整这里用到
NSDecimalNumberHandler
先定义一个枚举(Swift)
internal enum OperatorType{
//加
case addition
//减
case subtraction
//乘
case Multiplication
//除
case division
}
internal enum OperatorType{
//加
case addition
//减
case subtraction
//乘
case Multiplication
//除
case division
}
货币计算并向上取整的方法
首先根据字符串初始化两个NSDecimalNumber对象
然后初始化NSDecimalNumberHandler为条件限制,比如保留小数点位数,向上取整,四舍五入等
参数介绍: