ios Swift - 如果小数等于 0,如何从浮点数中删除小数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31390466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:51:32  来源:igfitidea点击:

Swift - How to remove a decimal from a float if the decimal is equal to 0?

iosswiftfloating-point

提问by Kali Aney

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? I'm displaying this number like this:

我用一位小数显示距离,如果它等于 0(例如:1200.0Km),我想删除这个小数,我怎么能快速做到这一点?我像这样显示这个数字:

let distanceFloat: Float = (currentUser.distance! as NSString).floatValue
distanceLabel.text = String(format: "%.1f", distanceFloat) + "Km"

回答by Frankie

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)
    }
}

回答by MirekE

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

回答by Ashok

extensionis 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


Sample Playground file is here.


示例 Playground 文件在这里

回答by Christopher Larsen

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

回答by Linus

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)

回答by Jaydip

In Swift 4try 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)

回答by Baig

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 format it to Int, follow this pattern

要将其格式化为 Int,请遵循以下模式

let aInt: Int = Int(aFloat) // "1"

回答by C?ur

Formatting with maximum fraction digits, without trailing zeros

使用最大小数位数进行格式化,不带尾随零

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

1.0 → "1"
0.12 → "0.12"
0.012 → "0.01"
0.0012 → "0"
0.00012 → "0"

1.0 → “1”
0.12 → “0.12”
0.012 → “0.01”
0.0012 → “0”
0.00012 → “0”

回答by vadian

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"

回答by Fine Man

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) {
  1. Strips the float's decimal digits with Int(number).
  2. Returns the stripped number back to float to do an operation with Float(Int(number)).
  3. Gets the decimal-digit value with number - Float(Int(number))
  4. Checks the decimal-digit value is empty with if number - Float(Int(number)) == 0
  1. 用 去除浮点数的十进制数字Int(number)
  2. 将剥离的数字返回给 float 以对 进行操作Float(Int(number))
  3. 获取十进制数字值 number - Float(Int(number))
  4. 检查十进制数字值是否为空 if number - Float(Int(number)) == 0

The contents within the if and else statements doesn't need explaining.

if 和 else 语句中的内容不需要解释。