[英]Swift - How to remove a decimal from a float if the decimal is equal to 0?
I'm displaying a distance with one decimal, and I would like to remove this decimal in case it is equal to 0 (ex: 1200.0Km), how could I do that in swift?我用一位小数显示距离,如果它等于 0(例如:1200.0Km),我想删除这个小数,我怎么能快速做到这一点? I'm displaying this number like this:
我像这样显示这个数字:
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: "%.1f", distanceFloat) + "Km"
Swift 3/4:斯威夫特 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
Swift 2 (Original answer) Swift 2(原始答案)
let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: distanceFloat == floor(distanceFloat) ? “%.0f" : "%.1f", distanceFloat) + "Km"
Or as an extension:或者作为扩展:
extension Float {
var clean: String {
return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
Use NSNumberFormatter:使用 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")
}
Returns:返回:
3 3
5.1 5.1
7.21 7.21
9.31 9.31
600 600
0.57 0.57
0.7 0.7
extension
is the powerful way to do it. extension
是做到这一点的强大方法。
Extension :扩展:
Code for Swift 2 (not Swift 3 or newer): Swift 2 代码(不是 Swift 3 或更新版本):
extension Float {
var cleanValue: String {
return self % 1 == 0 ? String(format: "%.0f", self) : String(self)
}
}
Usage :用法:
var sampleValue: Float = 3.234
print(sampleValue.cleanValue)
3.234
3.234
sampleValue = 3.0
print(sampleValue.cleanValue)
3
3
sampleValue = 3
print(sampleValue.cleanValue)
3
3
Update of accepted answer for swift 3 : Swift 3 已接受答案的更新:
extension Float
{
var cleanValue: String
{
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
usage would just be:用法只是:
let someValue: Float = 3.0
print(someValue.cleanValue) //prints 3
To format it to String, follow this pattern要将其格式化为字符串,请遵循以下模式
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"
To cast it to Int, follow this pattern要将其转换为 Int,请遵循以下模式
let aInt: Int = Int(aFloat) // "1"
When you use String(format:
initializer, Swift will automatically round the final digit as needed based on the following number.当您使用
String(format:
initializer) 时,Swift 将根据需要根据以下数字自动舍入最后一位数字。
You can use an extension as already mentioned, this solution is a little shorter though:您可以使用已经提到的扩展,不过这个解决方案要短一些:
extension Float {
var shortValue: String {
return String(format: "%g", self)
}
}
Example usage:用法示例:
var sample: Float = 3.234
print(sample.shortValue)
In Swift 4 try this.在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)//
}
}
//How to use - if you enter more then two-character after (.)point, it's automatically cropping the last character and only display two characters after the point. //如何使用 - 如果在 (.)point 后输入超过两个字符,它会自动裁剪最后一个字符,并且只显示该点后的两个字符。
let strValue = "32.12"
print(\(CGFloat(strValue).cleanValue)
Swift 5 for Double it's same as @Frankie's answer for float Swift 5 for Double 与@Frankie 对 float 的回答相同
var dec: Double = 1.0
dec.clean // 1
for the extension对于扩展
extension Double {
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
NSNumberFormatter is your friend 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"
This scenario is good when a custom output precision is desired.当需要自定义输出精度时,这种情况是很好的。 This solution seems roughly as fast as NumberFormatter + NSNumber solution from MirekE , but one benefit could be that we're avoiding NSObject here.
这个解决方案看起来与 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)])
}
}
(works also with extension Float
, but not the macOS-only type Float80
) (也适用于
extension Float
,但不适用于仅限 macOS 的类型Float80
)
Usage: myNumericValue.string(maximumFractionDigits: 2)
or myNumericValue.string()
用法:
myNumericValue.string(maximumFractionDigits: 2)
或myNumericValue.string()
Output for maximumFractionDigits: 2
: maximumFractionDigits: 2
输出maximumFractionDigits: 2
:
1.0 → "1"
1.0 → “1”
0.12 → "0.12"0.12 → “0.12”
0.012 → "0.01"0.012 → “0.01”
0.0012 → "0"0.0012 → “0”
0.00012 → "0"0.00012 → “0”
Here's the full code.这是完整的代码。
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
Here's the most important line in-depth.这是最重要的深入介绍。
func displayNumber(number: Float) {
Int(number)
.Int(number)
去除浮点数的十进制数字。Float(Int(number))
.Float(Int(number))
。number - Float(Int(number))
number - Float(Int(number))
if number - Float(Int(number)) == 0
if number - Float(Int(number)) == 0
检查十进制数字值是否为空The contents within the if and else statements doesn't need explaining. if 和 else 语句中的内容不需要解释。
简单的 :
Int(floor(myFloatValue))
This might be helpful too.这也可能有帮助。
extension Float {
func cleanValue() -> String {
let intValue = Int(self)
if self == 0 {return "0"}
if self / Float (intValue) == 1 { return "\(intValue)" }
return "\(self)"
}
}
Usage:用法:
let number:Float = 45.23230000
number.cleanValue()
Swift 5.5 makes it easy Swift 5.5让一切变得简单
Just use the new formatted()
api with a default FloatingPointFormatStyle
:只需使用带有默认
FloatingPointFormatStyle
的新formatted()
api:
let values: [Double] = [1.0, 4.5, 100.0, 7]
for value in values {
print(value.formatted(FloatingPointFormatStyle()))
}
// prints "1, 4.5, 100, 7"
Maybe stringByReplacingOccurrencesOfString
could help you :)也许
stringByReplacingOccurrencesOfString
可以帮助你:)
let aFloat: Float = 1.000
let aString: String = String(format: "%.1f", aFloat) // "1.0"
let wantedString: String = aString.stringByReplacingOccurrencesOfString(".0", withString: "") // "1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.