我想创建一个函数来查看字符串,如果它是十进制字符串,则将其作为货币格式的字符串返回。下面的函数就是这样做的,但是如果我传入一个已经格式化的字符串,它当然会失败(它希望看到像“25”或“25.55”这样的字符串,但不是 '15.25 美元'
有没有办法修改我下面的函数以添加另一个 if 条件,即“如果您已经被格式化为货币字符串,或者您的字符串格式不正确,则返回 X”(也许 X 将是0,或者可能是 self(相同的字符串)我还不确定)。
func toCurrencyStringFromDecimalString() -> String
{
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
if (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).utf16Count == 0)
{
//If whitespace is passed in, just return 0.0 as default
return numberFormatter.stringFromNumber(NSDecimalNumber(string: "0.0"))!
}
else if (IS_NOT_A_DECIMAL_OR_ALREADY_A_CURRENCY_STRING)
{
//So obviously this would go here to see if it's not a decimal (or already contains a current placeholder etc)
}
else
{
return numberFormatter.stringFromNumber(NSDecimalNumber(string: self))!
}
}
感谢您的帮助!
最佳答案
听起来您需要使用 NSScanner
。
根据docs , NSScanner
的scanDecimal
函数:
Skips past excess digits in the case of overflow, so the receiver’s position is past the entire integer representation.
Invoke this method with NULL as value to simply scan past a decimal integer representation.
我主要用 Obj-C 编程,所以我的 Swift 很垃圾,但这是我尝试翻译适当的代码来检测数字字符串(也在 this answer 中演示):
let scanner: NSScanner = NSScanner(string:self)
let isNumeric = scanner.scanDecimal(nil) && scanner.atEnd
如果字符串不是十进制表示,isNumeric
应该返回 false。
关于ios - 检查字符串是否已经是货币字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563062/