Hello !
I have this code
let myDouble: Double = 3.45
I want to keep the type as Double
but I want to remove the decimals
to get as result only 3 (no 3.45)
Are there some method to do that?
Thanks!
Hello !
I have this code
let myDouble: Double = 3.45
I want to keep the type as Double
but I want to remove the decimals
to get as result only 3 (no 3.45)
Are there some method to do that?
Thanks!
let result = myDouble.rounded(.towardZero) // 3
https://developer.apple.com/documentation/swift/floatingpoint/3017985-rounded
thanks @scanon !
Do you know some way to hide the decimals?
let result = 3.45.rounded(.towardZero) // result is 3.0. I would need 3 (without decimal, without zero)
Ah, that's a question of formatting, not rounding. The value is exactly 3, your question is just how to get it to print without any extra digits.
import Foundation
String(format: "%.0f", result)
Great! this is the solution
if you want more granular control over formatting there are the new formatters in Foundation (which that String(format:)
is also from)
result.formatted(.number.precision(.fractionLength(0)))
I want to remove the decimals to get as result only 3
There are various ways to do this but they divide into two groups:
Those that produce localised results.
Those that produce US ASCII results.
Which type of result do you want? Because:
If you want US ASCII results and you use a localised formatter, the Arabic digits you get in some environments will probably ruin your day (-:
Contrariwise, a user who’s expecting Arabic will not be happy with US ASCII results.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple