Answers for "swift double 2 decimal places"

5

format decimal place swift

let tip: Double = 15.2847320
let tipText: String = String(format: "%.2f", tip)
// %.2f for two decimal places
Posted by: Guest on March-14-2020
1

swift round double to 2 decimal places

You can use Swift's round function to accomplish this.

To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y)  // 1.236
Other than any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double.

EDIT:
Regarding the comments that it sometimes does not work, please read this:
Posted by: Guest on March-08-2021
1

xcode truncate number of decimal places of double

//Multiply the double you want to round by 10^(the number of decimal place precision you want), use the "round()" function, then divide by that number again

let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y)  // 1.236
Posted by: Guest on August-30-2020

Code answers related to "swift double 2 decimal places"

Code answers related to "Swift"

Browse Popular Code Answers by Language