我正在显示一个带小数点的距离,如果它等于0(例如:1200.0Km),我想删除此小数点,如何迅速做到这一点?我正在显示此数字,如下所示:
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: "%.1f", distanceFloat) + "Km"
我正在显示一个带小数点的距离,如果它等于0(例如:1200.0Km),我想删除此小数点,如何迅速做到这一点?我正在显示此数字,如下所示:
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: "%.1f", distanceFloat) + "Km"
Answers:
迅捷3/4:
var distanceFloat1: Float = 5.0
var distanceFloat2: Float = 5.540
var distanceFloat3: Float = 5.03
extension Float {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
print("Value \(distanceFloat1.clean)") // 5
print("Value \(distanceFloat2.clean)") // 5.54
print("Value \(distanceFloat3.clean)") // 5.03
斯威夫特2(原始答案)
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: distanceFloat == floor(distanceFloat) ? “%.0f" : "%.1f", distanceFloat) + "Km"
或作为扩展:
extension Float {
var clean: String {
return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
distanceFloat = floor(distanceFloat * 10) / 10
,然后效果很好,谢谢:)
使用NSNumberFormatter:
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
// Avoid not getting a zero on numbers lower than 1
// Eg: .5, .67, etc...
formatter.numberStyle = .decimal
let nums = [3.0, 5.1, 7.21, 9.311, 600.0, 0.5677, 0.6988]
for num in nums {
print(formatter.string(from: num as NSNumber) ?? "n/a")
}
返回值:
3
5.1
7.21
9.31
600
0.57
0.7
let formatter = NumberFormatter() formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 1 statLabel.text = formatter.string(from: value as NSNumber) ?? "n/a"
formatter.numberStyle = .decimal
.decimal
numberStyle ,则低于1的数字将显示为零。例如:.5,.78等...现在编辑答案。
extension
是执行此操作的有力方法。
扩展名:
Swift 2的代码(不是Swift 3或更高版本):
extension Float {
var cleanValue: String {
return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
用法:
var sampleValue: Float = 3.234
print(sampleValue.cleanValue)
3.234
sampleValue = 3.0
print(sampleValue.cleanValue)
3
sampleValue = 3
print(sampleValue.cleanValue)
3
示例游乐场文件在这里。
快速3接受答案的更新:
extension Float
{
var cleanValue: String
{
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
用法将是:
let someValue: Float = 3.0
print(someValue.cleanValue) //prints 3
要将其格式化为字符串,请遵循以下模式
let aFloat: Float = 1.123
let aString: String = String(format: "%.0f", aFloat) // "1"
let aString: String = String(format: "%.1f", aFloat) // "1.1"
let aString: String = String(format: "%.2f", aFloat) // "1.12"
let aString: String = String(format: "%.3f", aFloat) // "1.123"
要将其转换为Int,请遵循以下模式
let aInt: Int = Int(aFloat) // "1"
使用String(format:
初始值设定项时,Swift将根据以下数字自动舍入最后一位数字。
您可以使用已提到的扩展,但是此解决方案要短一些:
extension Float {
var shortValue: String {
return String(format: "%g", self)
}
}
用法示例:
var sample: Float = 3.234
print(sample.shortValue)
0.00000001
。请参阅pubs.opengroup.org/onlinepubs/009695399/functions/printf.html上%g的文档:“使用的样式取决于转换后的值;仅当转换产生的指数时才使用样式e(或E)是小于-4或大于或等于精度。 “
在Swift 4中试试这个。
extension CGFloat{
var cleanValue: String{
//return String(format: 1 == floor(self) ? "%.0f" : "%.2f", self)
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)//
}
}
//使用方法-如果在(。)点后输入两个字符,则该字符会自动裁剪最后一个字符,并且仅在该点后显示两个字符。
let strValue = "32.12"
print(\(CGFloat(strValue).cleanValue)
1.1
:输出将是"1.10"
。
NSNumberFormatter是你的朋友
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
let numberFormatter = NSNumberFormatter()
numberFormatter.positiveFormat = "###0.##"
let distance = numberFormatter.stringFromNumber(NSNumber(float: distanceFloat))!
distanceLabel.text = distance + " Km"
当需要自定义输出精度时,此方案很好。此解决方案似乎与MirekE的NumberFormatter + NSNumber解决方案一样快,但是一个好处是,我们在这里避免使用NSObject。
extension Double {
func string(maximumFractionDigits: Int = 2) -> String {
let s = String(format: "%.\(maximumFractionDigits)f", self)
var offset = -maximumFractionDigits - 1
for i in stride(from: 0, to: -maximumFractionDigits, by: -1) {
if s[s.index(s.endIndex, offsetBy: i - 1)] != "0" {
offset = i
break
}
}
return String(s[..<s.index(s.endIndex, offsetBy: offset)])
}
}
(也适用于extension Float
,但不适用于仅限macOS的类型Float80
)
用法:myNumericValue.string(maximumFractionDigits: 2)
或myNumericValue.string()
输出为maximumFractionDigits: 2
:
1.0→“ 1”
0.12→“ 0.12”
0.012→“ 0.01”
0.0012→“ 0”
0.00012→“ 0”
Swift 5 for Double与@Frankie的float答案相同
var dec: Double = 1.0
dec.clean // 1
对于扩展
extension Double {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
这是完整的代码。
let numberA: Float = 123.456
let numberB: Float = 789.000
func displayNumber(number: Float) {
if number - Float(Int(number)) == 0 {
println("\(Int(number))")
} else {
println("\(number)")
}
}
displayNumber(numberA) // console output: 123.456
displayNumber(numberB) // console output: 789
这是最重要的深度线。
func displayNumber(number: Float) {
Int(number)
。Float(Int(number))
。number - Float(Int(number))
if number - Float(Int(number)) == 0
if和else语句中的内容不需要解释。
String
而不是println(result)
do return result
。我希望这有帮助!
这也可能会有所帮助。
extension Float {
func cleanValue() -> String {
let intValue = Int(self)
if self == 0 {return "0"}
if self / Float (intValue) == 1 { return "\(intValue)" }
return "\(self)"
}
}
用法:
let number:Float = 45.23230000
number.cleanValue()
也许stringByReplacingOccurrencesOfString
可以帮助您:)
let aFloat: Float = 1.000
let aString: String = String(format: "%.1f", aFloat) // "1.0"
let wantedString: String = aString.stringByReplacingOccurrencesOfString(".0", withString: "") // "1"
1.05
执行String(format: "%.1f", aFloat)
将是1.0
有效的。如果1.05
executeString(format: "%.2f", aFloat)
将为1.05
,则应该执行此操作stringByReplacingOccurrencesOfString(".00"...)