如何转换字符串中的任何数字

时间:2019-04-09 09:31:51

标签: swift

假设我有一个数字 2000000 。 我想写成20 Lac。

我该如何解决?

我尝试将NSNumberFormatter与.spellout数字样式一起使用。

2 个答案:

答案 0 :(得分:1)

尝试

func formatNumber(_ n: Int) -> String {

    let num = abs(Double(n))
    let sign = (n < 0) ? "-" : ""

    switch num {

    case 10_000_000...:
        let formatted = num / 10_000_000
        return "\(sign)\(formatted.clean) Crore"

    case 100_000...:
        let formatted = num / 100_000
        return "\(sign)\(formatted.clean) Lac"

    case 1_000...:
        let formatted = num / 1_000
        return "\(sign)\(formatted.clean) Thousand"

    case 0...:
        return "\(n)"

    default:
        return "\(sign)\(n)"

    }
}

Double Extension在哪里

extension Double {
    var clean: String {
        return String(Int(self))
    }
}

并将产生以下结果

print(formatNumber(2000000)) // 20 Lac
print(formatNumber(1515)) // 1 Thousand
print(formatNumber(999999)) // 9 Lac
print(formatNumber(1000999)) // 10 Lac
print(formatNumber(103099900))// 10 Crore

答案 1 :(得分:1)

尝试一下:

    let actualAmount: Float = 103099900
    var currency = Double()


    var shortenedAmount: Float = actualAmount
    var suffix = ""
    currency = Double(shortenedAmount)
    if currency >= 10000000.0 {
        suffix = "C"
        shortenedAmount /= 10000000.0
    } else if currency >= 1000000.0 {
        suffix = "M"
        shortenedAmount /= 1000000.0
    } else if currency >= 100000.0 {
        suffix = "L"
        shortenedAmount /= 100000.0
    } else if currency >= 1000.0 {
        suffix = "K"
        shortenedAmount /= 1000.0
    }

    var numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    var numberAsString = numberFormatter.string(from: NSNumber(value: shortenedAmount))

    var requiredString = "\(numberAsString ?? "")\(suffix)"
    print(requiredString)

结果:

10.31C