首页 > 解决方案 > 在字母数字 NSString 中将 FLOATS 向上/向下舍入为 INTS

问题描述

我被这个困住了——</p>

我有一个字母数字的 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 提供了这个警告——</p>

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

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

任何帮助将不胜感激。

标签: iosobjective-cxcodexcode12

解决方案


我喜欢 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"

推荐阅读