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
SwiftUI: If you are truncating to format output in a view, but not computation, SwiftUI contains a convenient way to use C format specifiers as part of the signature for Text().
import SwiftUI
let myDouble = 17.93846938645960695
Text("\(myDouble, specifier: "%.2f")")
///Device display: 17.94
Above code will output the contents of Double directly to the View, rounded correctly to the hundredth place, but preserve the value of the Double for further calculations.
If as a user of SwiftUI you are unfamiliar with the C language format specifiers, this link contains helpful information: https://en.wikipedia.org/wiki/Printf_format_string
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))
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