如何在Swift中将小数截断为x位置

owl*_*ipe 10 double decimal calculator ios swift

在我的swift程序中,我有一个非常长的十进制数字(比如说17.9384693864596069567),我想将小数截断为几个小数位(所以我希望输出为17.9384).我希望数字四舍五入到17.9385.我怎样才能做到这一点?

感谢帮助!

注意:这不是重复的,因为在使用其中一些函数之前,它们使用的是旧版本的swift.此外,他们使用浮点数和整数,而我说的是双打.他们的问题/答案要复杂得多.

Rus*_*ell 27

你可以把它作为一个扩展来进一步整理它 Double

extension Double
{
    func truncate(places : Int)-> Double
    {
        return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
    }
}
Run Code Online (Sandbox Code Playgroud)

你像这样使用它

var num = 1.23456789
// return the number truncated to 2 places
print(num.truncate(places: 2))

// return the number truncated to 6 places
print(num.truncate(places: 6))
Run Code Online (Sandbox Code Playgroud)

  • 这对1以下的数字不起作用:(如果使用`0.23456789.truncate(2)`你会得到`0.23000000000000001` (5认同)
  • 我喜欢!如此有条理,当您使用它时实际上很有意义:)。 (2认同)
  • 很高兴你喜欢它 - 这是我写过的第一个扩展,所以我们今天都学到了一些东西:-) (2认同)

owl*_*ipe 8

我想通了这一点。

只是地板(四舍五入)数字,有一些花哨的技巧。

let x = 1.23556789
let y = Double(floor(10000*x)/10000) // leaves on first four decimal places
let z = Double(floor(1000*x)/1000) // leaves on first three decimal places
print(y) // 1.2355
print(z) // 1.235
Run Code Online (Sandbox Code Playgroud)

因此,乘以 1 和 0 的数量是您想要的小数位数,将其取整,然后除以乘以的数值。瞧。


Prc*_*ela 6

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(_ places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
    func cutOffDecimalsAfter(_ places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self*divisor).rounded(.towardZero) / divisor
    }
}

let a:Double = 1.228923598

print(a.roundToPlaces(2)) // 1.23
print(a.cutOffDecimalsAfter(2)) // 1.22
Run Code Online (Sandbox Code Playgroud)


TDe*_*ign 6

您可以通过以下方式保持简单:

String(format: "%.0f", ratio*100)
Run Code Online (Sandbox Code Playgroud)

其中 0 是您要允许的小数位数。在这种情况下为零。比率是双倍,例如:0.5556633。希望能帮助到你。


Ram*_*ami 5

小数点后特定数字的代码为:

let number = 17.9384693864596069567;
let merichle = Float(String(format: "%.1f", (number * 10000)).dropLast(2))!/10000

//merichle = 17.9384
Run Code Online (Sandbox Code Playgroud)

最终,您的数字会被截断而没有舍入……

  • @RamazanKarami String(format: "%.2f", b) 将舍入双精度数,而不是截断它。 (2认同)