Swift Double to String

Swift double to string

It is not casting, it is creating a string from a value with a format.

let a: Double = 1.5
let b: String = String(format: "%f", a)

print("b: \(b)") // b: 1.500000

With a different format:

let c: String = String(format: "%.1f", a)

print("c: \(c)") // c: 1.5

You can also omit the format property if no formatting is needed.

How to convert Long Double to String in swift

An even easier approach to format your Doubles without scientific notation would be to use String(format: "%.0f", data)

Note that Double cannot hold 44444444444444444.0 correctly, therefore you would probably get something like 44444444444444448 as output.

To get correct results you should use NSDecimalNumber, like this:

let decimalNumber = NSDecimalNumber(string: "44444444444444444.0")
print(decimalNumber.stringValue)

Swift 3 Convert Double to String

mealstats.serving is most probably of type "Double" and not "Double?"

Since it is not optional it cannot be unwrapped. The right way to use it would be

func displayStats() {
// display other attributes if they have values
servingsLabel.text = "\(mealstats.serving)"
}

iOS Swift - Convert double to String precision last value rounded to next value

If you use a NumberFormatter, you need to set the roundingMode to .floor to achieve truncating. Also, if you want to truncate, you probably want to set maximumFractionDigits instead of minimumFractionDigits.

extension Double {
var string: String {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 4
formatter.roundingMode = .floor
return formatter.string(for: self) ?? description
}
}

3.00035358.string // "3.0003"

Double to String in swiftUI

You are computing convertedValueString too early when the value of convertedValueRaw is 0. Move it to the end of the function:

var convertedFigure: String {

let valueInputted = Double(inputValue) ?? 0

var baseValueInMeters: Double = 0
var convertedValueRaw: Double = 0

// Move this ...
// let convertedValueString = String(convertedValueRaw)

switch selectedInputUnit {
case "meters":
baseValueInMeters = valueInputted
case "kilometers":
baseValueInMeters = valueInputted / 0.001
case "feet":
baseValueInMeters = valueInputted / 3.28
case "yards":
baseValueInMeters = valueInputted / 1.09
case "miles":
baseValueInMeters = valueInputted / 0.00062
default:
baseValueInMeters = 0
}

switch selectedOutputUnit {
case "meters":
convertedValueRaw = baseValueInMeters
case "kilometers":
convertedValueRaw = baseValueInMeters * 0.001
case "feet":
convertedValueRaw = baseValueInMeters * 3.28
case "yards":
convertedValueRaw = baseValueInMeters * 1.09
case "miles":
convertedValueRaw = baseValueInMeters * 0.00062
default:
baseValueInMeters = 0
}


// ... to here:
let convertedValueString = String(convertedValueRaw)

return convertedValueString

}

or simply convert and return at the same time:

return String(convertedValueRaw)

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

Convert very long Double to String in Swift

That's due to the imprecision of Double. If you use Decimal, you don't run into this issue.

You also don't need that workaround to add a leading 0, you should simply set minimumIntegerDigits to 1. You also don't need the conversion to NSNumber, NumberFormatter has a method string(for:) which accepts Swift numeric types (Double or Decimal for instance).

extension Decimal {
static let cleanFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 16
formatter.minimumIntegerDigits = 1
return formatter
}()

var clean: String {
let cleanedString = Decimal.cleanFormatter.string(for: self) ?? ""
return cleanedString
}
}

let decimalNum = Decimal(string: "12345678901234567000.0")!
decimalNum.clean // "12345678901234567000"
decimalNum.clean == "12345678901234567000" // true

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"
}

Swift - How to convert String to Double

Swift 4.2+ String to Double

You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.

Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).

let lessPrecisePI = Float("3.14")

let morePrecisePI = Double("3.1415926536")
let invalidNumber = Float("alphabet") // nil, not a valid number

Unwrap the values to use them using if/let

if let cost = Double(textField.text!) {
print("The user entered a value price of \(cost)")
} else {
print("Not a valid number: \(textField.text!)")
}

You can convert formatted numbers and currency using the NumberFormatter class.

let formatter = NumberFormatter()
formatter.locale = Locale.current // USA: Locale(identifier: "en_US")
formatter.numberStyle = .decimal
let number = formatter.number(from: "9,999.99")

Currency formats

let usLocale = Locale(identifier: "en_US")
let frenchLocale = Locale(identifier: "fr_FR")
let germanLocale = Locale(identifier: "de_DE")
let englishUKLocale = Locale(identifier: "en_GB") // United Kingdom
formatter.numberStyle = .currency

formatter.locale = usLocale
let usCurrency = formatter.number(from: "$9,999.99")

formatter.locale = frenchLocale
let frenchCurrency = formatter.number(from: "9999,99€")
// Note: "9 999,99€" fails with grouping separator
// Note: "9999,99 €" fails with a space before the €

formatter.locale = germanLocale
let germanCurrency = formatter.number(from: "9999,99€")
// Note: "9.999,99€" fails with grouping separator

formatter.locale = englishUKLocale
let englishUKCurrency = formatter.number(from: "£9,999.99")

Read more on my blog post about converting String to Double types (and currency).

Precision String Format Specifier In Swift

My best solution so far, following from David's response:

import Foundation

extension Int {
func format(f: String) -> String {
return String(format: "%\(f)d", self)
}
}

extension Double {
func format(f: String) -> String {
return String(format: "%\(f)f", self)
}
}

let someInt = 4, someIntFormat = "03"
println("The integer number \(someInt) formatted with \"\(someIntFormat)\" looks like \(someInt.format(someIntFormat))")
// The integer number 4 formatted with "03" looks like 004

let someDouble = 3.14159265359, someDoubleFormat = ".3"
println("The floating point number \(someDouble) formatted with \"\(someDoubleFormat)\" looks like \(someDouble.format(someDoubleFormat))")
// The floating point number 3.14159265359 formatted with ".3" looks like 3.142

I think this is the most Swift-like solution, tying the formatting operations directly to the data type. It may well be that there is a built-in library of formatting operations somewhere, or maybe it will be released soon. Keep in mind that the language is still in beta.



Related Topics



Leave a reply



Submit