ios - 检查字符串是否已经是货币字符串?

标签 ios swift ios8

我想创建一个函数来查看字符串,如果它是十进制字符串,则将其作为货币格式的字符串返回。下面的函数就是这样做的,但是如果我传入一个已经格式化的字符串,它当然会失败(它希望看到像“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 , NSScannerscanDecimal 函数:

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/

相关文章:

ios - 为 iOS 应用程序存储数据的最佳方法?

ios - numberOfRowsInSection/3 - 只返回 15 张图像而不是 16 或 17,因为它们不能被 3 整除

ios - 如何在不包装旧库的情况下让 OAuth2 与 SwiftUI 一起使用?

ios - Xcode Swift 委托(delegate),VC 实例化时新值被覆盖

ios - 为 2 个 imageView 的位置切换设置动画

ios - 使用通用 Codable API 客户端处理非 JSON 响应

ios - 在 iOS 7 手机上使用 iOS 8 功能,hidesBarsOnSwipe

android - 汇编程序可以在 OS X、iOS 和 Android 上运行吗?

ios - 在 iOS8 上,以横向模式显示我的应用程序会隐藏状态栏,但在 iOS 7 上,状态栏会同时显示在两个方向上

ios - 在 iOS 8 上,ALAssetsLibrary 不显示所有的 "Saved Photos"而只显示 "Recently added"