简体   繁体   English

在Objective-C中将货币字符串转换为浮点数

[英]Convert currency string into float in Objective-C

My goal is simple, I have a textfield storing a localized currency value ($1,000.00 for instance) and I need to get that value back from the textfield as a float to perform some test on the textfield. 我的目标很简单,我有一个存储本地化货币值的文本字段(例如$ 1,000.00),我需要从文本字段中获取该值作为浮点数来对文本字段执行某些测试。

The code is really simple, first I format the NSNumber to a localizedString as so : 代码非常简单,首先我将NSNumber格式化为localizedString,如下所示:

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
textfield.text = [formatter stringFromNumber:number];

Everything works fine, but then I do the opposite to get the doubleValue from this localized string : 一切正常,但我做相反的事情从这个本地化的字符串得到doubleValue:

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.numberStyle = NSNumberFormatterCurrencyStyle; //also tested with NSNumberFormatterDecimalStyle

double d = [formatter numberFromString:textfield.text].doubleValue;

The problem is that the formatter only returns the integer value of my string and not the decimals, worse, if it is a canadian localizedstring (20 000,00 $) it only returns 20. 问题是格式化程序只返回我的字符串的整数值而不是小数,更糟糕的是,如果它是加拿大本地化字符串(20 000,00 $),它只返回20。

I've been searching for some time now and can't find anything about this behavior. 我一直在寻找一段时间,但却找不到任何关于这种行为的信息。 The workaround is of course storing the NSNumber right before formating it to the textfield and then testing this nsnumber, but I really don't find it pretty. 解决方法当然是在将NSNumber格式化到文本字段然后测试这个nsnumber之前存储它,但我真的不觉得它很漂亮。

In Swift, you can do this by similarly setting the locale to the format of the currency, and then getting the double: 在Swift中,您可以通过类似地将语言环境设置为货币格式,然后获取双精度来实现此目的:

    var locale = NSLocale.currentLocale()
    var formatter = NSNumberFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US")
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle

    var moneyDouble = formatter.numberFromString(textField.text)?.doubleValue

正如朱塞佩所指出的那样,答案非常简单,我正在抨击我的头靠在墙上,因为没有考虑它。

double d = [NSDecimalNumber decimalNumberWithString:textfield.text locale:[NSLocale currentLocale]].doubleValue;

A slight enhancement to zavtra's answer that returns a float and doesn't force the locale identifier to be en_US (Swift 2): 对zavtra的回答略有增强,它返回一个浮点数并且不强制语言环境标识符为en_US (Swift 2):

func floatFromTextFieldText() -> Float {
    let formatter = NSNumberFormatter()
    formatter.locale = NSLocale.currentLocale()
    formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
    guard let amount = self.text else { return 0.0 }
    return formatter.numberFromString(amount)!.floatValue
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM