How to truncate decimals to x places in Swift

2020-02-13 08:18发布

问题:

In my swift program, I have a really long decimal number (say 17.9384693864596069567) and I want to truncate the decimal to a few decimal places (so I want the output to be 17.9384). I do not want to round the number to 17.9385. How can I do this?

Help is appreciated!

Note: This is not a duplicate because they are using a very old version of swift, before some of these functions were made. Also, they are using floats and integers, whereas I am talking about doubles. And their question/answers are much more complicated.

回答1:

You can tidy this up even more, by making it an extension of Double

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

and you use it like this

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


回答2:

The code for specific digits after decimals is:

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

//merichle = 17.9384

And ultimately, your number gets truncate without round...



回答3:

I figured this one out.

Just floor (round down) the number, with some fancy tricks.

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

So, multiply by 1 and the number of 0s being the decimal places you want, floor that, and divide it by what you multiplied it by. And voila.



回答4:

Drag/Drop Solution, IOS, Swift 4

Copy this code into your application...

import Foundation

func truncateDigitsAfterDecimal(number: Double, afterDecimalDigits: Int) -> Double {
   if afterDecimalDigits < 1 || afterDecimalDigits > 512 {return 0.0}
   return Double(String(format: "%.\(afterDecimalDigits)f", number))!
}

Then you can call this function like:

truncateDigitsAfterDecimal(number: 45.123456789, afterDecimalDigits: 3)

Will produce the following:

45.123


回答5:

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.cutOfDecimalsAfter(2)) // 1.22