Programing

Swift-소수점이 0과 같으면 부동 소수점에서 소수점을 제거하는 방법?

lottogame 2020. 11. 19. 07:47
반응형

Swift-소수점이 0과 같으면 부동 소수점에서 소수점을 제거하는 방법?


소수점 하나로 거리를 표시하고 있는데, 0 (예 : 1200.0Km) 인 경우이 소수점을 제거하고 싶습니다. 어떻게 신속하게 할 수 있습니까? 이 번호를 다음과 같이 표시합니다.

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

스위프트 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 (원래 답변)

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

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

보고:

5.1

7.21

9.31

600

0.57

0.7


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)

sampleValue = 3
print(sampleValue.cleanValue)


샘플 플레이 그라운드 파일은 여기에 있습니다 .


신속한 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

이미 언급 한대로 확장을 사용할 수 있지만이 솔루션은 조금 더 짧습니다.

extension Float {
    var shortValue: String {
        return String(format: "%g", self)
    }
}

사용 예 :

var sample: Float = 3.234
print(sample.shortValue)

문자열로 형식을 지정하려면 다음 패턴을 따르십시오.

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"

In Swift 4 try this.

    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.

let strValue = "32.12"
print(\(CGFloat(strValue).cleanValue)

NSNumberFormatter is your friend

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"

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

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


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.

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)

Usage: myNumericValue.string(maximumFractionDigits: 2) or myNumericValue.string()

Output for maximumFractionDigits: 2:

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


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

Maybe stringByReplacingOccurrencesOfString could help you :)

let aFloat: Float = 1.000

let aString: String = String(format: "%.1f", aFloat) // "1.0"

let wantedString: String = aString.stringByReplacingOccurrencesOfString(".0", withString: "") // "1"

참고URL : https://stackoverflow.com/questions/31390466/swift-how-to-remove-a-decimal-from-a-float-if-the-decimal-is-equal-to-0

반응형