我正在寻找一种在不使用TextField hack的情况下将字符串格式化为货币的方法。
例如,我希望将数字“521242”转换为“5,212.42” 或者,如果我的数字低于1美元,我希望它看起来像这样:“52” - > “0.52”
由于
答案 0 :(得分:66)
你可能想要这样的东西(假设货币是浮动的):
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
s。这将极大地减少带有舍入误差的麻烦。如果您执行此操作,则上面的代码段变为(假设货币为NSDecimalNumber*
):
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:currency];
答案 1 :(得分:12)
我使用此代码。这项工作对我来说
1)将UITextField Delegate添加到头文件
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; }
答案 2 :(得分:3)
使用以下代码,它将解决您的所有问题......
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[currency doubleValue]]];
答案 3 :(得分:2)
这是我发现使用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;
}
答案 4 :(得分:1)
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!
}
注意: - 货币代码是三字母代码,在大多数情况下, 由一个国家的双字符互联网国家代码加上 一个额外的字符来表示货币单位。例如, 澳元的货币代码是“澳元”。
答案 5 :(得分:1)
对于Swift测试代码(参考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
}
注意:如果您想从输入中删除默认货币符号,可以使用currencySymbol为空白,如下所示
currencyFormatter.currencyCode = nil
currencyFormatter.currencySymbol = ""
快乐的编码!
答案 6 :(得分:0)
使用格式化程序的一件事是它们的创建成本很高。最好为每个视图或视图控制器创建一次。使用 lazy
是避免这种开销的完美解决方案。这也将许多样板文件移出了主代码。
class MyViewController: UIViewController {
@IBOutlet var priceLabel: UILabel!
private lazy var currencyFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.currencySymbol = "$"
formatter.numberStyle = .currency
return formatter
}()
// rest of class
}
要使用它,如别处所述,最好使用 Decimal
表示货币,Double
是近似值。
priceLabel.text = currencyFormatter.string(for: Decimal(9.48))
输出:
$9.48