Luko
(Luciano Schillagi)
1
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!
scanon
(Steve Canon)
2
2 Likes
Luko
(Luciano Schillagi)
4
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)
scanon
(Steve Canon)
5
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)
2 Likes
Luko
(Luciano Schillagi)
6
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)))
8 Likes
eskimo
(Quinn “The Eskimo!”)
8
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:
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