Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a proper way to convert a Double to a Float in Swift? [closed]

Tags:

ios

swift

I'm trying to convert a double being retrieved from an iPhone sensor into a float. Unfortunately, I can't seem to find any resources on built in functionality to do so.

If I initialize a Float or a cast to a Float from a double like so:

let roll  = (Float)(attitude!.roll)
let pitch  = (Float)(attitude!.pitch)

Or

let roll = Float(attitude!.roll)
let pitch = Float(attitude!.pitch)

the original Double values still don't get converted properly. For instance, 9.436222 and 27.895268 become 0.486864 and 0.164693 respectively. Is there a proper way to cast to a Float from a Double that preserves the larger decimal value?

like image 922
Gabriel Garrett Avatar asked Jun 01 '16 19:06

Gabriel Garrett


People also ask

How is double converted to Float?

Using TypeCasting to Convert Double to Float in Java To define a float type, we must use the suffix f or F , whereas it is optional to use the suffix d or D for double. The default value of float is 0.0f , while the default value of double is 0.0d . By default, float numbers are treated as double in Java.

Should I use double or Float Swift?

Swift enforces you to use Doubles instead of Floats. You should use Float only if you want to sacrifice precision to save memory. Also, if you are working with types that require Float, then you have to use a Float.

What is CGFloat in Swift?

Swift version: 5.6. A CGFloat is a specialized form of Float that holds either 32-bits of data or 64-bits of data depending on the platform. The CG tells you it's part of Core Graphics, and it's found throughout UIKit, Core Graphics, Sprite Kit and many other iOS libraries.

Can you assign Float double?

The doubleValue() method of Java Float class returns a double value corresponding to this Float Object by widening the primitive values or in simple words by directly converting it to double via doubleValue() method .


1 Answers

guard let unwrappedAttitude = attitude else { 
    fatalError("attitude was nil!")
}

let roll = Float(unwrappedAttitude.roll)
let pitch = Float(unwrappedAttitude.pitch)

should be the way to go.

like image 192
Alexander Avatar answered Sep 18 '22 14:09

Alexander