Swift: Double Conversion Inconsistency. How to Correctly Compare Doubles

Swift isPowerofThree can not pass 243

This is due to the precision of Double. Numbers a coded in binary format and at some point the precision you expect can't reached.

I tried your program and log3(243) give me 4.9999999...
So it make sense the modulo 1 fail.

If you change Double to Float, your program will works.

if log3(Float(n)) % 1 == 0.0

func log3(val: Float) -> Float

Why are doubles printed differently in dictionaries?

As already mentioned in the comments, a Double cannot store
the value 1.1 exactly. Swift uses (like many other languages)
binary floating point numbers according to the IEEE 754
standard.

The closest number to 1.1 that can be represented as a Double is

1.100000000000000088817841970012523233890533447265625

and the closest number to 2.3 that can be represented as a Double is

2.29999999999999982236431605997495353221893310546875

Printing that number means that it is converted to a string with
a decimal representation again, and that is done with different
precision, depending on how you print the number.

From the source code at HashedCollections.swift.gyb one can see that the description method of
Dictionary uses debugPrint() for both keys and values,
and debugPrint(x) prints the value of x.debugDescription
(if x conforms to CustomDebugStringConvertible).

On the other hand, print(x) calls x.description if x conforms
to CustomStringConvertible.

So what you see is the different output of description
and debugDescription of Double:

print(1.1.description) // 1.1
print(1.1.debugDescription) // 1.1000000000000001

From the Swift source code one can see
that both use the swift_floatingPointToString()
function in Stubs.cpp, with the Debug parameter set to false and true, respectively.
This parameter controls the precision of the number to string conversion:

int Precision = std::numeric_limits<T>::digits10;
if (Debug) {
Precision = std::numeric_limits<T>::max_digits10;
}

For the meaning of those constants, see std::numeric_limits:

  • digits10 – number of decimal digits that can be represented without change,
  • max_digits10 – number of decimal digits necessary to differentiate all values of this type.

So description creates a string with less decimal digits. That
string can be converted to a Double and back to a string giving
the same result.
debugDescription creates a string with more decimal digits, so that
any two different floating point values will produce a different output.

Execution of combined Booleans in swift

&& is a “short-circuiting” operator: If the left operand is false then the right operand is not evaluated at all.

Here are two possible options if you want (for debugging purposes) all boolean expressions to be evaluated.

Option 1: Create an array with all boolean results before combining them:

if [check1, check2, check3].allSatisfy({ $0 }) { ... }

Option 2: Define your own “logical AND” operator which does not short-circuit:

infix operator &&&: LogicalConjunctionPrecedence

extension Bool {
static func &&&(left: Bool, right: Bool) -> Bool {
left && right
}
}

if check1 &&& check2 &&& check3 { ... }

There are probably more ways to achieve this.

iOS Swift - Convert String with $ to Double

You could take a "brute force" approach and remove all non-numerics characters from the string and use the internal type conversions directly.

let numberString     = "135,05 kr"
let decimalSeparator = Locale.current.decimalSeparator ?? "."
let decimalFilter = CharacterSet(charactersIn:"-0123456789" + decimalSeparator)
let number = Float(numberString.components(separatedBy:decimalFilter.inverted)
.joined(separator:""))

This will clean up any non numeric characters from the string. So it will not be affected by inconsistent thousand separators or variations of the currency symbol (e.g. if you're working with multiple currencies). You do have to be consistent on the decimal separators though.



Related Topics



Leave a reply



Submit