36

我正在寻找一种在不使用 TextField hack 的情况下将字符串格式化为货币的方法。

例如,我想将数字“521242”转换为“5,212.42”或者如果我有一个低于 1 美元的数字,我希望它看起来像这样:“52”->“0.52”

谢谢

4

8 回答 8

67

你可能想要这样的东西(假设货币是浮动的):

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:currency]];

根据您将 52 视为 0.52 的要求,您可能需要除以 100.0。

这种方法的好处是它将尊重当前的语言环境。因此,它会在适当的情况下将您的示例格式化为“5.212,42”。

更新: 我发布示例的速度可能有点快。正如下面康拉德舒尔茨所指出的,在处理货币金额时,最好将数量存储为NSDecimalNumbers。这将大大减少舍入错误带来的麻烦。如果你这样做,上面的代码片段变成(假设货币是 a NSDecimalNumber*):

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:currency];
于 2012-08-03T00:44:20.667 回答
12

我使用此代码。这对我有用

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; }
于 2012-08-03T00:46:29.550 回答
6

迅捷2.0版本:

    let _currencyFormatter : NSNumberFormatter = NSNumberFormatter()
    _currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    _currencyFormatter.currencyCode = "EUR"
    textField.text = _currencyFormatter.stringFromNumber(amount);
于 2015-09-10T12:17:19.440 回答
3

使用以下代码,它将解决您的所有问题....

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[currency doubleValue]]];
于 2013-02-07T11:03:38.633 回答
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;
}
于 2014-01-18T06:42:03.177 回答
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!
}

注意:- 货币代码是三个字母的代码,在大多数情况下,由一个国家的两个字符的互联网国家代码加上一个额外的字符组成,以表示货币单位。例如,澳元的货币代码是“AUD”。

于 2015-11-02T03:44:14.817 回答
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 = ""

快乐编码!

于 2016-09-22T09:05:19.930 回答
0

使用格式化程序的一件事是创建它们的成本很高。最好为每个视图或视图控制器创建一次。Usinglazy是避免这种开销的完美解决方案。这也将许多样板代码移到了主代码之外。

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
于 2021-04-01T16:02:46.983 回答