Koray Yavic
Koray Yavic

Reputation: 93

Implicit type of constant in swift tutorial

When I do example from tutorial, I get some issue from constants variables topic.

If someone explain my example I'll be appreciate for this.

enter image description here

Upvotes: 1

Views: 68

Answers (1)

Sweeper
Sweeper

Reputation: 270790

When you don't specify a type, a floating point number literal will be inferred to be of type Double.

Double, as its name suggests, has double precision than Float. So when you do:

let a = 64.1

The actual value in memory may be something like 64.099999999999991. Since Double shows only 16 significant digits, it shows 64.09999999999999, rounding off the last "1".

Why does let b: Float = 64.1 show the correct number?

When you specify the type to float, the precision decreases. Float only shows 8 significant digits. That's 64.099999, but there's a "9" straight after that, so it rounds it up to get 64.1.

This has nothing to do with explicitly stating the variable type. Try specifying it to be a Double:

let b: Double = 64.1

It will still show 64.09999999999999.

Upvotes: 1

Related Questions