Swift - Remove Trailing Zeros From Double

前端 未结 4 1330
栀梦
栀梦 2021-01-03 19:07

What is the function that removes trailing zeros from doubles?

var double = 3.0
var double2 = 3.10

println(func(double)) // 3
println(func(double2)) // 3.1
         


        
相关标签:
4条回答
  • 2021-01-03 19:12

    Removing trailing zeros in output

    This scenario is good when the default output precision is desired. We test the value for potential trailing zeros, and we use a different output format depending on it.

    extension Double {
        var stringWithoutZeroFraction: String {
            return truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
        }
    }
    

    (works also with extension Float, but not Float80)

    Output:

    1.0 → "1"
    0.1 → "0.1"
    0.01 → "0.01"
    0.001 → "0.001"
    0.0001 → "0.0001"

    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)
            for i in stride(from: 0, to: -maximumFractionDigits, by: -1) {
                if s[s.index(s.endIndex, offsetBy: i - 1)] != "0" {
                    return String(s[..<s.index(s.endIndex, offsetBy: i)])
                }
            }
            return String(s[..<s.index(s.endIndex, offsetBy: -maximumFractionDigits - 1)])
        }
    }
    

    (works also with extension Float, but not Float80)

    Output for maximumFractionDigits: 2:

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

    Note that it performs a rounding (same as MirekE solution):

    0.9950000 → "0.99"
    0.9950001 → "1"

    0 讨论(0)
  • 2021-01-03 19:27

    In case you're looking how to remove trailing zeros from a string:

    string.replacingOccurrences(of: "0*$", with: "", options: .regularExpression)
    

    This will transform strings like "0.123000000" into "0.123"

    0 讨论(0)
  • 2021-01-03 19:28

    In Swift 4 you can do it like that:

    extension Double {
        func removeZerosFromEnd() -> String {
            let formatter = NumberFormatter()
            let number = NSNumber(value: self)
            formatter.minimumFractionDigits = 0
            formatter.maximumFractionDigits = 16 //maximum digits in Double after dot (maximum precision)
            return String(formatter.string(from: number) ?? "")
        }
    }
    

    example of use: print (Double("128834.567891000").removeZerosFromEnd()) result: 128834.567891

    You can also count how many decimal digits has your string:

    import Foundation
    
    extension Double {
        func removeZerosFromEnd() -> String {
            let formatter = NumberFormatter()
            let number = NSNumber(value: self)
            formatter.minimumFractionDigits = 0
            formatter.maximumFractionDigits = (self.components(separatedBy: ".").last)!.count
            return String(formatter.string(from: number) ?? "")
        }
    }
    
    0 讨论(0)
  • 2021-01-03 19:39

    You can do it this way but it will return a string:

    var double = 3.0
    var double2 = 3.10
    
    func forTrailingZero(temp: Double) -> String {
        var tempVar = String(format: "%g", temp)
        return tempVar
    }
    
    forTrailingZero(double)   //3
    forTrailingZero(double2)  //3.1
    
    0 讨论(0)
提交回复
热议问题