ios 如何在ios上正确格式化货币

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11787759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:34:28  来源:igfitidea点击:

How to properly format currency on ios

iphoneiosnumberscurrencyformatter

提问by Fran?ois Marceau

I'm looking for a way to format a string into currency without using the TextField hack.

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

For example, i'd like to have the number "521242" converted into "5,212.42" Or if I have a number under 1$, I would like it to look like this: "52" -> "0.52"

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

Thanks

谢谢

回答by idz

You probably want something like this (assuming currency is a float):

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

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

From your requirements to treat 52 as .52 you may need to divide by 100.0.

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

The nice thing about this approach is that it will respect the current locale. So, where appropriate it will format your example as "5.212,42".

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

Update:I was, perhaps, a little speedy in posting my example. As pointed out by Conrad Shultz below, when dealing with currency amounts, it would be preferable to store the quantities as NSDecimalNumbers. This will greatly reduce headaches with rounding errors. If you do this the above code snippet becomes (assuming currency is a NSDecimalNumber*):

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

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

回答by AAV

I use this code. This work for me

我用这个代码。这对我有用

1) Add UITextField Delegate to header file

1) 将 UITextField Delegate 添加到头文件中

2) Add this code (ARC enabled)

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; }

回答by Bill Chan

swift 2.0 version:

快速 2.0 版本:

    let _currencyFormatter : NSNumberFormatter = NSNumberFormatter()
    _currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    _currencyFormatter.currencyCode = "EUR"
    textField.text = _currencyFormatter.stringFromNumber(amount);

回答by james lobo

Use the following code and it will resolve all your issues....

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

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

回答by Joe Collins

This is what I have found reworking AAV answer using NSDecimalNumbers.

这是我发现使用 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;
}

回答by Vikram Pote

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!
}

Note:- A currency code is a three-letter code that is, in most cases, composed of a country's two-character Internet country code plus an extra character to denote the currency unit. For example, the currency code for the Australian dollar is “AUD”.

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

回答by Hardik Thakkar

For Swift tested code (ref from AAV's code)

对于 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
}

note : if you want to remove the default currency symbol from input you can use currencySymbol to blank as below

注意:如果您想从输入中删除默认货币符号,您可以使用货币符号来空白,如下所示

currencyFormatter.currencyCode = nil
currencyFormatter.currencySymbol = ""

Happy coding!

快乐编码!