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

时间:2015-07-13 18:10:49

标签: ios swift floating-point

我正在显示一个带小数的距离,如果它等于0(例如:1200.0Km),我想删除这个小数,我怎么能在swift中做到这一点? 我正在显示这样的数字:

return new HtmlString(string.Format("<input type='submit' id='btnShowFault' onclick='ShowFaultMessage(\"{0}\")' value='Fault' />", item.Fault.Message));

15 个答案:

答案 0 :(得分:73)

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

答案 1 :(得分:67)

使用NSNumberFormatter:

cmd.exe

返回:

3

5.1

7.21

9.31

600

0.57

0.7

答案 2 :(得分:53)

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


示例Playground文件为here

答案 3 :(得分:28)

更新swift 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

答案 4 :(得分:7)

你可以使用已经提到的扩展,但这个解决方案有点短:

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

使用示例:

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

答案 5 :(得分:6)

要将其格式化为String,请遵循此模式

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"

答案 6 :(得分:6)

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)

答案 7 :(得分:4)

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"

答案 8 :(得分:4)

雨燕5 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)
    }

}

答案 9 :(得分:3)

以下是完整的代码。

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) {
  1. 使用Int(number)删除浮点数的十进制数字。
  2. 将已剥离的数字返回到float以使用Float(Int(number))执行操作。
  3. 使用number - Float(Int(number))
  4. 获取小数位数值
  5. 使用if number - Float(Int(number)) == 0
  6. 检查小数位数值是否为空

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

答案 10 :(得分:2)

这也可能有用。

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

答案 11 :(得分:2)

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

当需要自定义输出精度时,此方案很好。 此解决方案似乎与NumberFormatter + NSNumber solution from MirekE一样快,但是一个好处可能是我们在这里避免使用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”

答案 12 :(得分:0)

简单:

Int(floor(myFloatValue))

答案 13 :(得分:0)

Swift 5.5 让一切变得简单

只需使用带有默认 formatted() 的新 FloatingPointFormatStyle 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"

答案 14 :(得分:-1)

也许{"Columbus Herzog": [{"source":"Las Cruces Crawford Arpt (LRU)","amount":"5000.0","points":"500","date_time":"Sat Feb 13 02:18:14 IST 2016","class":"First","destination":"San Luis Arpt (IPI)"}], [{"source":"Las Cruces Crawford Arpt (LRU)","amount":"5000.0","points":"500","date_time":"Fri Jul 22 01:52:19 IST 2016","class":"First","destination":"San Luis Arpt (IPI)"}], [{"source":"Las Cruces Crawford Arpt (LRU)","amount":"5000.0","points":"500","date_time":"Wed Jan 06 06:24:50 IST 2016","class":"First","destination":"San Luis Arpt (IPI)"}], [{"source":"Las Cruces Crawford Arpt (LRU)","amount":"5000.0","points":"500","date_time":"Tue May 17 17:12:16 IST 2016","class":"First","destination":"San Luis Arpt (IPI)"}] } 可以帮到你:)

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
  </head>

  <body>
    <h1>Hello Plunker!</h1>
    <div class="container">
      <div class="row">
      <div class="col-md-4">
        hello
      </div>
      <div class="col-md-8">
        hello i am trying to insert this content inside the parent div,but i am not able to do so. My content should be inside the border of this div and i want the height not to be fixed as my content is dynamic.
      </div>
      </div>
    </div>
  </body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="https://getbootstrap.com/dist/js/bootstrap.min.js"></script>
  <script src="https://getbootstrap.com/assets/js/ie10-viewport-bug-workaround.js"></script>
</html>