1

I have the structure as follows:

struct Foo {
    var number: Double

    public init(number: Double) {
        self.number = number
    }
}

but when i run this code ->

var x: Double = 1.12
let foo = Foo(number: x)

print(foo)
print(foo.number)

I get following output:

Foo(number: 1.1200000000000001)
1.12

I think this because of double precision but don't know how to handle it. Any help is very appreciated!

Andrey M.
  • 3,021
  • 29
  • 42

1 Answers1

1

As in answer explained by @MartinR, Why are doubles printed differently in dictionaries?

It is clear that 1.1200000000000001, is the double precision value of 1.12.

While you are trying to print foo object, print(foo) object is getting printed along with its enclosed information in which number holds the double precisied value of 1.21

Whereas, when you directly print(foo.number), then string representation of foo.number is getting printed which is actually 1.21

Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36