You're using generic initializer init(_:)
which creates an integer from the given floating-point value, rounding toward zero.
So, there is well known problem with saving types based on floating point math (see this). Because of that, your a
can be saved for example as 3.99999999999999994
. Then, if you use this Int
initalizer from this Double
, it creates Int
rounded toward zero... (3
)
One way is rounding your Double
value before it will be passed for Int
initializer to one decimal place
round(a*10)/10
and then round result by following rule
>= 0.5 round up
< 0.5 round down
For this purpose you can use rounded
method with FloatingPointRoundingRule
.toNearestOrAwayFromZero
(which is default value for this parameter)
var a: Double = 3.499999999
var b = Int((round(a*10)/10).rounded()) // b = 4
Also you can use failable initalizer, since if Double
is bigger then Int
can be, code crashes
var a: Double = .greatestFiniteMagnitude
if var b = Int(exactly: (round(a*10)/10).rounded()) { ... } // nil