Используйте NumberFormatter с .roundingMode = .down
let nf = NumberFormatter()
nf.roundingMode = .down
// max of 2 decimal places (e.g. 1.23, 1.2, 1)
nf.maximumFractionDigits = 2
// starting with Strings
["65.788", "1.2", "1.9", "1"].forEach { s in
let n = Float(s)
let t = nf.string(for: n)
print("[" + t! + "]")
}
// starting with Numbers
[65.788, 1.2, 1.9, 1].forEach { n in
let t = nf.string(for: n)
print("[" + t! + "]")
}
// if you want exactly 2 decimal places (e.g. 1.23, 1.20, 1.00)
nf.minimumFractionDigits = 2
// starting with Strings
["65.788", "1.2", "1.9", "1"].forEach { s in
let n = Float(s)
let t = nf.string(for: n)
print("[" + t! + "]")
}
// starting with Numbers
[65.788, 1.2, 1.9, 1].forEach { n in
let t = nf.string(for: n)
print("[" + t! + "]")
}
Вывод:
[65.78]
[1.2]
[1.9]
[1]
[65.78]
[1.2]
[1.9]
[1]
[65.78]
[1.20]
[1.90]
[1.00]
[65.78]
[1.20]
[1.90]
[1.00]
Очевидно, вы хотите использовать проверку ошибок, чтобы убедиться, что ваши исходные строки могут преобразовать в числа и т. Д. *