Issue with Swift Floats inside Structs

二次信任 提交于 2019-12-25 02:19:06

问题


I'm having an issue where swift is changing my float value when it's inside a struct.. I dont think this happened on older versions of swift, but it is happening now on 4.1. Code example below... thoughts?

var f = Float(4.111)

print(f) // prints 4.111

struct FloatContainer {
    var f: Float
}

let container = FloatContainer(f: f)

print(container) // prints FloatContainer(f: 4.11100006)

回答1:


That's a common rounding error, since binary can't represent some decimal numbers. Have a look here.

Here is an online converter from a decimal to a floating-point representation. As you can see there is an error (6.103515625E-8) due to the conversion:

As to the difference between when you print a float directly, or when you print an object that has a property that is a float, it comes down to the description property of objects that implement the CustomStringConvertible protocol. When the print function wants to print to the console, it invokes _print_unlocked, which is an internal function that has this block:

if case let printableObject as CustomStringConvertible = value {
    printableObject.description.write(to: &target)
    return
}

So you could change your code to this in order to have the expected output:

struct FloatContainer : CustomStringConvertible {
    var description: String {
        get {
            return f.description
        }
    }
    var f: Float
}



回答2:


You should try printing the value inside

print(container.f) // prints 4.111

This is returning what you are storing.




回答3:


Swift provides default debug representation for any type and this is the reason Apple documentation

 var f = Float(4.111)

    print(f) // prints 4.111

    print(f.debugDescription) // prints 4.11100006
    print(String(reflecting: f)) // default presentation according to documentation: prints 4.11100006

    struct FloatContainer: CustomStringConvertible {
        var f: Float

        // You can achieve similar output to `print(f)` with conforming
        // to `CustomStringConvertible` and implementing custom 
        // `description` implementation
        var description: String {
            return f.description
        }
    }

    let container = FloatContainer(f: f)
    // After our custom implementation the result of `print` 
    // method is the same to print(f)
    print(container) // prints FloatContainer(f: 4.111)


来源:https://stackoverflow.com/questions/52006079/issue-with-swift-floats-inside-structs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!