iOS 货币交易输入数字检测 小数点前面三位,小数点后允许两位,并且向上取整(无精度丢失问题)

2017-03-21 08:22:58来源:CSDN作者:xutianyu930818人点击

第七城市th7cn

首先是数字检测 正则表达式 小数点前面三位,小数点后允许两位

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}



货币计算并向上取整的方法


首先根据字符串初始化两个NSDecimalNumber对象
然后初始化NSDecimalNumberHandler为条件限制,比如保留小数点位数,向上取整,四舍五入等
参数介绍:

roundingMode:
    NSRoundPlain,   // Round up on a tie //这个暂时未尝试,大家可以自己试下

    NSRoundDown,    // Always down == truncate  //只舍不入

    NSRoundUp,      // Always up    // 只入不舍

    NSRoundBankers  // on a tie round so last digit is even  这个暂时未尝试,大家可以自己试下
scale:int类型,保留几位小数
raiseOnExactness:如果为true,如果发生精度(还是精确?)错误,则处理程序将引发异常,否则将忽略错误并将控制返回到调用方法。
raiseOnOverflow:如果为true,如果发生溢出错误,则处理程序将引发异常,否则将忽略错误并将控制返回到调用方法
raiseOnUnderflow: 如果为true,如果出现下溢错误,则处理程序将引发异常,否则将忽略错误并将控制返回到调用方法
raiseOnDivideByZero:如果为true,如果发生除以零错误 处理程序将引发异常,否则将忽略错误,并返回控制的调用方法

Objective - c代码
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler                                       decimalNumberHandlerWithRoundingMode:NSRoundBankers                                       scale:2                                       raiseOnExactness:NO                                       raiseOnOverflow:NO                                       raiseOnUnderflow:NO                                       raiseOnDivideByZero:YES];


Swift 代码
let roundingBehavior = NSDecimalNumberHandler.init(                                                            roundingMode: NSDecimalNumber.RoundingMode.up,                                                           scale: Int16(position),                                                           raiseOnExactness: false,                                                           raiseOnOverflow: false,                                                           raiseOnUnderflow: false,                                                           raiseOnDivideByZero: false)


加减乘除方法(每个运算符有两个方法,从上到下是加减乘除,总共八个方法)




Objective-c
- (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber;- (NSDecimalNumber *)decimalNumberByAdding:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;//这两个是加法- (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber;- (NSDecimalNumber *)decimalNumberBySubtracting:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;//减法- (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber;- (NSDecimalNumber *)decimalNumberByMultiplyingBy:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;//乘法- (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber;- (NSDecimalNumber *)decimalNumberByDividingBy:(NSDecimalNumber *)decimalNumber withBehavior:(nullable id <NSDecimalNumberBehaviors>)behavior;//除法



Swift
    
    open func adding(_ decimalNumber: NSDecimalNumber) -> NSDecimalNumber    open func adding(_ decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber        open func subtracting(_ decimalNumber: NSDecimalNumber) -> NSDecimalNumber    open func subtracting(_ decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber        open func multiplying(by decimalNumber: NSDecimalNumber) -> NSDecimalNumber    open func multiplying(by decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber        open func dividing(by decimalNumber: NSDecimalNumber) -> NSDecimalNumber    open func dividing(by decimalNumber: NSDecimalNumber, withBehavior behavior: NSDecimalNumberBehaviors?) -> NSDecimalNumber






调用示例
    NSDecimalNumber *subtotal = [NSDecimalNumberdecimalNumberWithString:@"90.7049"];    NSDecimalNumber *discount = [NSDecimalNumberdecimalNumberWithString:@"0.22"];    NSDecimalNumber *total = [subtotal decimalNumberByAdding:discount withBehavior:roundUp];


最后附上源代码(Swift版)
////  XTYUtil.swift//  CreditBank////  Created by XuTianyu on 2017/3/20.//  Copyright © 2017年 lakala. All rights reserved.//import UIKitinternal enum OperatorType{    //加    case addition    //减    case subtraction    //乘    case Multiplication    //除    case division}class XTYUtil: NSObject {    /// 货币计算,向上取整    ///    /// - Parameters:    ///   - multiplierValue: value1    ///   - multiplicandValue: value2    ///   - position:需要保留的小数点位数    /// - Returns:保留好位数的字符串     internal class func decimalNumberWithString(multiplierValue:String,multiplicandValue:String,type:OperatorType, position:Int) -> String {                let multiplierNumber = NSDecimalNumber.init(string: multiplierValue)        let multiplicandNumber = NSDecimalNumber.init(string: multiplicandValue)                let roundingBehavior = NSDecimalNumberHandler.init(                                                            roundingMode: NSDecimalNumber.RoundingMode.up,                                                           scale: Int16(position),                                                           raiseOnExactness: false,                                                           raiseOnOverflow: false,                                                           raiseOnUnderflow: false,                                                           raiseOnDivideByZero: false)        var product : NSDecimalNumber        switch type {        case .addition:            product = multiplierNumber.adding(multiplicandNumber, withBehavior: roundingBehavior)            break        case .subtraction:            product = multiplierNumber.subtracting(multiplicandNumber, withBehavior: roundingBehavior)            break        case .Multiplication:            product = multiplierNumber.multiplying(by: multiplicandNumber, withBehavior: roundingBehavior)            break        default:            product = multiplierNumber.dividing(by: multiplicandNumber, withBehavior: roundingBehavior)            break        }        return String(format: "%./(position)f", product.doubleValue)    }    }

第七城市th7cn

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台