String Interpolation in Swift

A function in swift accepts any number type in Swift (Int, Double, Float, UInt, etc.). function converts a number to a string

function signature is as follows:

func swiftNumbers <T : NumericType> (number : T) -> String {
    //body
}

NumericType is a custom protocol that has been added to numeric types in Swift.

inside the function body, the number must be converted to a string:

I use the following

var stringFromNumber = "\(number)"

which is not so elegant, PLUS: if the absolute value of the number is strictly inferior to 0.0001, it gives the following:

"\(0.000099)" //"9.9e-05"

or if the number is a large number:

"\(999999999999999999.9999)" //"1e+18"

Is there a way around this string interpolation limitation? (without using Objective-C)

PS:

NumberFormater not working either

import Foundation

let number : NSNumber = 9_999_999_999_999_997

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 20
formatter.minimumIntegerDigits = 20
formatter.minimumSignificantDigits = 40

formatter.string(from: number) // "9999999999999996.000000000000000000000000"

let stringFromNumber = String(format: "%20.20f", number) // "0.00000000000000000000"
+4
source share
2 answers

Swift String: String(format: <#String#>, arguments: <#[CVarArgType]#>) : let stringFromNumber = String(format: "%.2f", number)

+4

Swift String

1)

2) , , , .

:

let length:Float = 3.14
var breadth = 10
var myString = "Area of a rectangle is length*breadth"
myString = "\(myString) i.e. = \(length)*\(breadth)"    

:

3.14
10
Area of a rectangle is length*breadth
Area of a rectangle is length*breadth i.e. = 3.14*10
+2

All Articles