Kotlin 是否有标准方法将数字格式化为英文序数?

问题描述 投票:0回答:3

在 Swift 中,我可以做这样的事情:

let ordinalFormatter = NumberFormatter()
ordinalFormatter.numberStyle = .ordinal

print(ordinalFormatter.string(from: NSNumber(value: 3))) // 3rd

但我看不出有什么方法可以在 Kotlin 中如此轻松地做到这一点。有没有这样的方法,还是我必须使用第3方库或自己编写?

int kotlin tostring ordinals
3个回答
14
投票

嗯,通常很难证明某件事不存在。但我从未在

kotlin-stdlib
中遇到过任何可以执行此操作或可以立即为此进行调整的函数。此外,
kotlin-stdlib
似乎不包含任何特定于语言环境的内容(当然是数字序数)。

我想你实际上应该求助于一些第三方软件或实现自己的解决方案,这可能就像这样简单:

fun ordinalOf(i: Int) {
    val iAbs = i.absoluteValue // if you want negative ordinals, or just use i
    return "$i" + if (iAbs % 100 in 11..13) "th" else when (iAbs % 10) {
        1 -> "st"
        2 -> "nd"
        3 -> "rd"
        else -> "th"
    }
}

另外,Java 中的解决方案:(此处)


2
投票

这是我的看法,@hotkey 解决方案的一个变体:

    fun Int.ordinal() = "$this" + when {
        (this % 100 in 11..13) -> "th"
        (this % 10) == 1 -> "st"
        (this % 10) == 2 -> "nd"
        (this % 10) == 3 -> "rd"
        else -> "th"
    }

调用,例如

13.ordinal()


0
投票
fun Int.toOrdinalNumber(): String {
    if (this in 11..13) {
        return "${this}th"
    }

    return when (this % 10) {
        1 -> "${this}st"
        2 -> "${this}nd"
        3 -> "${this}rd"
        else -> "${this}th"
    }
}

在这段代码中,在 Int 类中添加了 getOrdinalNumber 扩展函数。它首先检查数字是否在 11 到 13 范围内,因为在这些情况下,序数始终是“th”。对于其他情况,它会检查数字的最后一位数字并相应地附加“st”、“nd”或“rd”。如果这些条件都不匹配,则会附加“th”。 Int 类中添加了扩展函数。它首先检查数字是否在 11 到 13 范围内,因为在这些情况下,序数始终是“th”。对于其他情况,它会检查数字的最后一位数字并相应地附加“st”、“nd”或“rd”。如果这些条件都不匹配,则会附加“th”。

© www.soinside.com 2019 - 2024. All rights reserved.