【问题标题】:Rounding up/down FLOATS to INTS in alphanumeric NSString在字母数字 NSString 中将 FLOATS 向上/向下舍入为 INTS
【发布时间】:2021-03-02 02:58:56
【问题描述】:

我被这个卡住了——

我有一个字母数字的 NSString。字符串中的数字包含多个小数,我想将这些数字四舍五入为整数。

字符串如下所示:
VALUES: A:123.45678 B:34.55789 C:2.94567

我正在尝试使用此代码:
[self log:[NSString stringWithFormat:@"VALUES: %.f\n", values.toString]];

转换为:
值:A:123 B:35 C:3

Xcode 提供了这个警告——

Format specifies type 'double' but the argument has type 'NSString *'
Replace '%.1f' with '%@'

我认为我需要一种不同的方式来“扫描”字符串,识别数字并根据需要进行向上/向下舍入,然后将其转换为新字符串。我只是每次尝试都失败了。

任何帮助将不胜感激。

【问题讨论】:

  • 使用 NSScanner!它会找到数字。

标签: ios objective-c xcode xcode12


【解决方案1】:

我喜欢 NSScanner 的这种东西。这是一个 Swift 解决方案;不好意思,懒得翻译成Objective-C了,有点间接:

let s = "VALUES: A:123.45678 B:34.55789 C:2.94567"
let sc = Scanner(string:s)
sc.charactersToBeSkipped = nil
var arr = [String]()
while (true) {
    if let prefix = sc.scanUpToCharacters(from: .decimalDigits) {
        arr.append(prefix)
    } else { break }
    if let num = sc.scanDouble() {
        let rounded = num.rounded()
        arr.append(String(Int(rounded)))
    } else { break }
}
let result = arr.joined()
print(result) // "VALUES: A:123 B:35 C:3"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多