How to convert Double to Int in Swift?
You can use:
Int(yourDoubleValue)
this will convert double to int.
or when you use String format use 0 instead of 1:
String(format: "%.0f", yourDoubleValue)
this will just display your Double value with no decimal places, without converted it to int.
how to convert Double to Int in IOS swift
The casting of the Double to an Int will work as written. The problem is that for some reason at runtime self.motion.magnetometerData is nil, so tmp becomes nil.
It's usually better to safely unwrap optionals, such as:
let tmp = self.motion.magnetometerData?.magneticField.x
if let tmpValue = tmp {
let tmpInt = Int(tmpValue)
print(tmpInt) //And whatever else
}
Or, if you intend not to continue if it ends up being nil, use a guard:
guard let tmp = self.motion.magnetometerData?.magneticField.x else {
return //Or whatever is appropriate when the value is nil
}
How to convert double to int and display it on Text in swiftUI?
You can achieve all format like as below example
let doubleValue : Double = 5.33435
Text("\(String(format: "%.1f", doubleValue))") ---> 5.3
Text("\(String(format: "%.2f", doubleValue))") ---> 5.33
Text("\(String(format: "%.3f", doubleValue))") ---> 5.334
So, You can use String formating for this like as below
Text("Here: \(String(format: "%.0f", myViewModel.myModel.doubleValue))")
.font(.body)
Here is output
Accept Float, Double or Int in Swift `init` to convert to String
Actually if all you want is a string representation of Int
Float
Double
or any other standard numeric type you only need to know that they conform to CustomStringConvertible
and use String(describing:)
.
Or you can use conformance to Numeric
and CustomStringConvertible
:
struct example {
var string: String
init<C: CustomStringConvertible & Numeric>(number: C) {
string = String(describing: number)
}
}
and maybe even better example
itself could conform to CustomStringConvertible
struct example: CustomStringConvertible {
var description: String
init<C: CustomStringConvertible & Numeric>(number: C) {
description = String(describing: number)
}
}
yet another way :
struct example<N: Numeric & CustomStringConvertible>: CustomStringConvertible {
let number: N
init(number: N) {
self.number = number
}
var description: String {
String(describing: number)
}
}
EDIT
I think what you want is a custom Property Wrapper not @Binding
:
@propertyWrapper struct CustomStringConversion<Wrapped: CustomStringConvertible> {
var wrappedValue: Wrapped
init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
var projectedValue: String { .init(describing: wrappedValue) }
}
struct Foo {
@CustomStringConversion var number = 5
}
let foo = Foo()
let number: Int = foo.number // 5
let stringRepresentation: String = foo.$number // "5"
But as @LeoDabus pointed out using LosslessStringConvertible
may be better :
struct example<N: Numeric & LosslessStringConvertible>: LosslessStringConvertible {
let number: N
init(number: N) {
self.number = number
}
init?(_ description: String) {
guard let number = N(description) else { return nil }
self.number = number
}
var description: String {
.init(number)
}
}
let bar = example(number: Double.greatestFiniteMagnitude) // 1.7976931348623157e+308
let baz: example<Double>? = example("1.7976931348623157e+308") // 1.7976931348623157e+308
Display Double as Int if it is a whole number in Swift
Convert Double into Number and then to String if u want to show it on label
let i = 1.0
let j = 1.2345
// Value in String
let a = NSNumber(value: j).stringValue // "1.2345"
let b = NSNumber(value: i).stringValue // "1"
// Value in Double
let c = NSNumber(value: i).doubleValue // 1.0
let d = NSNumber(value: j).doubleValue // 1.2345
Converting String to Double/Float loses precision for large numbers in Swift 5
If you want to keep your floating precision you need to use Decimal type and make sure to use its string initializer:
let value = "0.0000335651599321165"
if let decimal = Decimal(string: value) {
print(decimal)
}
This will print:
0.0000335651599321165
edit/update:
When displaying your value to the user with a fixed number of fraction digits you can use Number Formatter and you can choose a rounding mode as well:
extension Formatter {
static let number = NumberFormatter()
}
extension Numeric {
func fractionDigits(min: Int = 6, max: Int = 6, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
Formatter.number.minimumFractionDigits = min
Formatter.number.maximumFractionDigits = max
Formatter.number.roundingMode = roundingMode
Formatter.number.numberStyle = .decimal
return Formatter.number.string(for: self) ?? ""
}
}
let value = "0.0000335651599321165"
if let decimal = Decimal(string: value) {
print(decimal.fractionDigits()) // "0.000034\n"
}
Related Topics
Cannot Assign Property in Method of Struct
Swift - Spritekit Cgpoint Alignment
Instance Member Cannot Be Used on Type of Custom Class
How to Encode a String to Base64 in Swift
What Is Geometry Reader in Swiftui
Getting "File Not Found" in Bridging Header When Importing Objective-C Frameworks into Swift Project
How to Get the Name of Enumeration Value in Swift
Can Swift Convert a Class/Struct Data into Dictionary
Can You Execute an Applescript Script from a Swift Application
Main Thread Checker: Ui API Called on a Background Thread: -[Uiapplication Applicationstate]
How to Create Generic Protocols in Swift
How to Remove Diacritics from a String in Swift
How to Check If a Firebase Database Value Exists
Extend Array Types Using Where Clause in Swift