ios - 在字母数字 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 '%@'
我认为我需要一种不同的方式来“扫描”字符串,识别数字并根据需要进行向上/向下舍入,然后将其转换为新字符串。我只是每次尝试都失败了。
任何帮助将不胜感激。
解决方案
我喜欢 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"
推荐阅读
- javascript - 为什么这个休息参数在这里有用?
- javascript - 创建一个 html 表,其中输入在里面
- javascript - 如何修复“TypeError:无法读取未定义的属性 'id'”错误?
- prometheus - promql 重命名vector()的结果
- java - 扩展 JMeter 时以编程方式获取/设置 JMeter 变量
- python - 在 simpletransformers 中为 NER 使用 CoNLL 数据格式时出现类型错误
- azure - 请求具有“公开 API”范围的令牌时出错。AADSTS70011:输入参数“范围”的提供值无效
- mongodb - 在 mongo shell 中取消设置 const
- sql - 在 postgresSQL 中获取一个月的最后一天和第一天的时间戳
- python - 如何使用 Python 在 OS X 中重新加载已安装的字体?