I am adding two array which contains double values
let arrayA = [1.1,2.3]
let arrayB = [4.2,5.5,6.8]
let c = arrayA + arrayB
print(\"\\(c)\");
You need to change as below :
defind type of array because you have not defined at now .
let arrayA : [CGFloat] = [1.1,2.3]
let arrayB : [CGFloat] = [4.2,5.5,6.8]
The reason for what you are seeing (1.1
-> 1.1000000000000001
) lies in the nature of floating points. It is caused by rounding errors, as the infinite nature of real numbers can not be presented in its finite memory (floating point) representation.
This might not be a big issue in your case, as you can change the printed format as stated in other answers, but can cause hard to track bugs, especially when comparing floating point numbers. For instance, the following code:
let result = 1.1 * 3.0
if result == 3.3 {
print("I thought so!")
} else {
print("This might be unexpected")
}
prints:
This might be unexpected
For more information I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic:
You don't. It's the way Double
(and Float
) does work.
As workaround you can round your values when you are going to print them
for num in c {
print(String(format: "%.1f", num))
}
1.1
2.3
4.2
5.5
6.8