简体   繁体   English

如何从 Swift 中的 Float 值创建 Double 值

[英]How to create a Double value from a Float value in Swift

I can't believe that I can't figure this out myself and I also cant find an answer online, but...我无法相信我自己无法解决这个问题,而且我也无法在网上找到答案,但是......

I'm working in Swift after a long break working on Dart and Java.在 Dart 和 Java 长时间休息后,我在 Swift 工作。

I have a situation where I have component A supplying a Float value, and component B requiring a Double value.我有一种情况,组件 A 提供 Float 值,而组件 B 需要 Double 值。 I can't figure out how to convert/cast/re-instantiate the float to a double!我不知道如何将浮点数转换/转换/重新实例化为双精度数!

Example:例子:

let f:Float = 0.3453
let d:Double = aVal; 

That assignment doesn't work, even though if f had been an Int, it would have.该分配不起作用,即使如果 f 是 Int,它也会起作用。 Which is very surprising to me since a Float is less precise than Double (takes less memory).这让我非常惊讶,因为 Float 不如 Double 精确(占用更少的内存)。

I also tried:我也试过:

let d:Double = f as! Double

XCode warns that this will "always fail." XCode 警告说这将“总是失败”。

Also tried:还尝试过:

let d:Double = Double(from: f)

XCode warns "f should be decoder type" XCode 警告“f 应该是解码器类型”

There has to be an extremely obvious/easy solution to this.必须有一个非常明显/简单的解决方案。

As @workingdog said, this will work:正如@workingdog 所说,这将起作用:

let f: Float = 0.3453
let d: Double = Double(f)

print(d) // prints 0.34529998898506165

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM