如何在iOS上正确格式化货币
我正在寻找一种方法来格式化string到货币没有使用TextField黑客。
例如,我想将数字“521242”转换为“5,212.42”或者如果我有1 $以下的数字,我希望它看起来像这样:“52” – >“0.52”
谢谢
你可能想要这样的东西(假设货币是一个浮动):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle]; NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:currency]];
根据你的要求把52当作.52你可能需要除以100.0。
这种方法的好处是它会尊重当前的语言环境。 因此,在适当的情况下,它会将您的示例格式化为“5.212,42”。
更新:或许,我发布自己的例子有点快。 正如下面的康拉德·舒尔茨(Conrad Shultz)所指出的那样,在处理货币数量时,最好将数量存储为NSDecimalNumber
。 这将大大减less令人头痛的错误。 如果你这样做,上面的代码片段变成(假设货币是一个NSDecimalNumber*
):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle]; NSString *numberAsString = [numberFormatter stringFromNumber:currency];
我使用这个代码。 这为我工作
1)将UITextField委托添加到头文件
2)添加这个代码(启用ARC)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *cleanCentString = [[textField.text componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""]; // Parse final integer value NSInteger centAmount = cleanCentString.integerValue; // Check the user input if (string.length > 0) { // Digit added centAmount = centAmount * 10 + string.integerValue; } else { // Digit deleted centAmount = centAmount / 10; } // Update call amount value NSNumber *amount = [[NSNumber alloc] initWithFloat:(float)centAmount / 100.0f]; // Write amount with currency symbols to the textfield NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init]; [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [_currencyFormatter setCurrencyCode:@"USD"]; [_currencyFormatter setNegativeFormat:@"-¤#,##0.00"]; textField.text = [_currencyFormatter stringFromNumber:amount]; return NO; }
swift 2.0版本:
let _currencyFormatter : NSNumberFormatter = NSNumberFormatter() _currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle _currencyFormatter.currencyCode = "EUR" textField.text = _currencyFormatter.stringFromNumber(amount);
使用下面的代码,它会解决你所有的问题….
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle]; NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[currency doubleValue]]];
这是我发现重新使用NSDecimalNumbers AAV答案。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *cleanCentString = [[textField.text componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""]; // Parse final integer value NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithMantissa:[cleanCentString integerValue] exponent:-2 isNegative:NO]; NSDecimalNumber *entry = [NSDecimalNumber decimalNumberWithMantissa:[string integerValue] exponent:-2 isNegative:NO]; NSDecimalNumber *multiplier = [NSDecimalNumber decimalNumberWithMantissa:1 exponent:1 isNegative:NO]; NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO]; NSDecimalNumber *result; // Check the user input if (string.length > 0) { // Digit added result = [price decimalNumberByMultiplyingBy:multiplier withBehavior:handler]; result = [result decimalNumberByAdding:entry]; } else { // Digit deleted result = [price decimalNumberByDividingBy:multiplier withBehavior:handler]; } // Write amount with currency symbols to the textfield NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init]; [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [_currencyFormatter setCurrencyCode:@"USD"]; textField.text = [_currencyFormatter stringFromNumber:result]; return NO; }
func getCurrencyFormat(price:String)->String{ let convertPrice = NSNumber(double: Double(price)!) let formatter = NSNumberFormatter() formatter.numberStyle = .CurrencyStyle formatter.currencyCode = "USD" let convertedPrice = formatter.stringFromNumber(convertPrice) return convertedPrice! }
注意: – 货币代码是一个三字母代码,在大多数情况下,由一个国家的两个字符的互联网国家代码加上一个额外的字符来表示货币单位。 例如,澳元的货币代码是“澳元”。
对于Swifttesting代码(来自AAV代码的参考)
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{ let strMain : NSString = string let arrTemp : NSArray = (textField.text?.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet))! let str: NSString = arrTemp.componentsJoinedByString("") //NSInteger centAmount = cleanCentString.integerValue; var centAmount : NSInteger = str.integerValue if (string.length > 0) { // Digit added centAmount = centAmount * 10 + strMain.integerValue; } else { // Digit deleted centAmount = centAmount / 10; } let amount = (Double(centAmount) / 100.0) let currencyFormatter = NSNumberFormatter() currencyFormatter.numberStyle = .CurrencyStyle currencyFormatter.currencyCode = "USD" currencyFormatter.negativeFormat = "-¤#,##0.00" let convertedPrice = currencyFormatter.stringFromNumber(amount) print(convertedPrice) txtAmount.text = convertedPrice! //set text to your textfiled return false //return false for exact out put }
注意:如果您想从input中删除默认的货币符号,您可以使用currencySymbol空白如下
currencyFormatter.currencyCode = nil currencyFormatter.currencySymbol = ""
快乐的编码!