本文介绍了如何在ios上正确格式化货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如,我想要的号码为521242 转换成5,212.42
如果我的数字低于1美元,我希望它看起来像这样:52 - >0.52

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"

谢谢

推荐答案

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

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

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

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

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

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".

更新:
我或许是发布我的例子有点快。如下面的Conrad Shultz所指出的,在处理货币金额时,最好将数量存储为 NSDecimalNumber s。这将大大减少带有舍入误差的麻烦。如果你这样做,上面的代码片段变为(假设货币是 NSDecimalNumber * ):

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*):

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

这篇关于如何在ios上正确格式化货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 09:46