Identificatore di formato di stringa di precisione in Swift


395

Di seguito è riportato come avrei precedentemente troncato un float con due decimali

NSLog(@" %.02f %.02f %.02f", r, g, b);

Ho controllato i documenti e l'eBook ma non sono stato in grado di capirlo. Grazie!

Risposte:


277

La mia migliore soluzione finora, a seguito della risposta di David :

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

Penso che questa sia la soluzione più rapida, collegando le operazioni di formattazione direttamente al tipo di dati. Può darsi che ci sia una libreria integrata di operazioni di formattazione da qualche parte, o forse verrà rilasciata presto. Tieni presente che la lingua è ancora in beta.


76
Questo è inutilmente complicato. la risposta di realityone funziona ed è molto più concisa.
Steven Marlowe,

9
Sicuro se lo stai usando solo una volta. Ma se volessi avere più opzioni di formattazione usando l'interpolazione di stringhe (che è molto più leggibile), allora potresti mettere tutte le estensioni di formattazione in un file altrove e fare riferimento a tutto il tuo progetto. Naturalmente, idealmente Apple dovrebbe fornire la libreria di formattazione.
Anton Tcholakov,

2
Questa soluzione non funzionerà in Swift 1.2 senza trasmettere il risultato a String.
ibesora,

Bello, ma non Swift 2 Friend.
LastMove

798

un modo semplice è:

import Foundation // required for String(format: _, _)

print(String(format: "hex string: %X", 123456))
print(String(format: "a float number: %.5f", 1.0321))

9
println(String(format: "a float number: %.5f", 1.0321))
zaph,

78
Credo che questa sia una risposta migliore della risposta accettata. È molto più vicino allo stile c standard printfsenza dover scrivere estensioni separate.
Keith Morris,

9
Non dimenticare la "import Foundation" nella parte superiore del file.
Chris Gregg,

3
È meglio della risposta accettata, ma utilizza ancora i metodi Foundation (collegati a Swift).

1
Assicurati diimport Foundation
NaN

125

Ho trovato String.localizedStringWithFormatche funziona abbastanza bene:

Esempio:

let value: Float = 0.33333
let unit: String = "mph"

yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)

La domanda non ha nulla a che fare con le unità di gestione. localizedStringWithFormat è carino, ma non correlato.
AmitP

Concordo con AmitP, è stato chiesto prima che String (formato: ..., argomenti: ...) fosse disponibile
Valentin

84

Questo è un modo molto veloce e semplice che non ha bisogno di una soluzione complessa.

let duration = String(format: "%.01f", 3.32323242)
// result = 3.3

Questo non viene compilato (utilizzando 3.0.2 nella sandbox Swift di IBM):Col 16: 'init' has been renamed to 'init(describing:)'
Peter Dillinger

@PeterDillinger stai passando un valore facoltativo anziché non scartato.
Michael,

63

La maggior parte delle risposte qui sono valide. Tuttavia, nel caso in cui formatterai spesso il numero, considera di estendere la classe Float per aggiungere un metodo che restituisce una stringa formattata. Vedi il codice di esempio di seguito. Questo raggiunge lo stesso obiettivo utilizzando un formattatore di numeri e un'estensione.

extension Float {
    func string(fractionDigits:Int) -> String {
        let formatter = NSNumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.stringFromNumber(self) ?? "\(self)"
    }
}

let myVelocity:Float = 12.32982342034

println("The velocity is \(myVelocity.string(2))")
println("The velocity is \(myVelocity.string(1))")

La console mostra:

The velocity is 12.33
The velocity is 12.3

Aggiornamento SWIFT 3.1

extension Float {
    func string(fractionDigits:Int) -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = fractionDigits
        formatter.maximumFractionDigits = fractionDigits
        return formatter.string(from: NSNumber(value: self)) ?? "\(self)"
    }
}

12
Vorrei che più persone usassero NSNumberFormatter, come questa risposta. Le altre risposte altamente votate non riescono semplicemente a riflettere le impostazioni locali del dispositivo (ad esempio, in alcune versioni locali, usano una virgola per una cifra decimale; ciò riflette ciò; altre risposte no).
Rob

3
L'unico miglioramento che mi piacerebbe vedere è la memorizzazione del formatter per un dato numero: i NSNumberFormatter sono costosi da costruire.
Kendall Helmstetter Gelner,

1
esattamente quello che stavo cercando! Grazie
gunjot singh

So che questa è una domanda piuttosto vecchia, ma NSNumberFormatterè abbastanza lenta da inizializzare. Se possibile, aiuta a definirne uno e riutilizzarlo. Detto questo, sto leggendo questa domanda perché non è possibile nel mio caso.
promacuser,

44

Non puoi farlo (ancora) con l'interpolazione di stringhe. La tua scommessa migliore sarà ancora la formattazione NSString:

println(NSString(format:"%.2f", sqrt(2.0)))

Estrapolando da Python, sembra che una sintassi ragionevole potrebbe essere:

@infix func % (value:Double, format:String) -> String {
    return NSString(format:format, value)
}

Che poi ti permette di usarli come:

M_PI % "%5.3f"                // "3.142"

Puoi definire operatori simili per tutti i tipi numerici, sfortunatamente non ho trovato il modo di farlo con generici.

Swift 5 Update

Almeno Swift 5 Stringsupporta direttamente l' format:inizializzatore, quindi non è necessario utilizzarlo NSStringe l' @infixattributo non è più necessario, il che significa che gli esempi sopra dovrebbero essere scritti come:

println(String(format:"%.2f", sqrt(2.0)))

func %(value:Double, format:String) -> String {
    return String(format:format, value)
}

Double.pi % "%5.3f"         // "3.142"

dove hai trovato quella sintassi `NSString (format:" formatString ", val) '. Non lo vedo nel documento iBooks di Apple.
Duncan C,

1
È lo stesso che costruire qualsiasi oggetto-obiettivo da rapido. È la versione rapida di[NSString stringWithFormat...
David Berry,

Gotcha. Non sono ancora arrivato così lontano nell'iBook Swift.
Duncan C,

IIRC che non era nell'iBook Swift. Era in una delle sessioni del WWDC.
Rapida

2
Se stai implementando% come in Python, dovrebbe essere il contrario. "% 5.3f"% M_PI
Andy Dent,

16

Perché renderlo così complicato? È possibile utilizzare questo invece:

import UIKit

let PI = 3.14159265359

round( PI ) // 3.0 rounded to the nearest decimal
round( PI * 100 ) / 100 //3.14 rounded to the nearest hundredth
round( PI * 1000 ) / 1000 // 3.142 rounded to the nearest thousandth

Guardalo funzionare nel parco giochi.

PS: Soluzione da: http://rrike.sh/xcode/rounding-various-decimal-places-swift/


Questa è di gran lunga la soluzione migliore, non capisco come questa non sia al top.
pjtnt11,

7
cosa nitpicky .. 1.500000000 sarebbe solo "1.5" e non "1.50"
styler1972

13
import Foundation

extension CGFloat {
    var string1: String {
        return String(format: "%.1f", self)
    }
    var string2: String {
        return String(format: "%.2f", self)
    }
}

uso

let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6

10

Una soluzione più elegante e generica è quella di riscrivere l' %operatore ruby / python :

// Updated for beta 5
func %(format:String, args:[CVarArgType]) -> String {
    return NSString(format:format, arguments:getVaList(args))
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]

Purtroppo questo muore in beta 6: errore fatale: impossibile non sicuro BitCast tra tipi di dimensioni diverse.
binarymochi,

@binarymochi Con Beta 6: "Hello %@, This is pi : %.2f" % ["World", M_PI]funziona, ma stranamente "%@ %@" % ["Hello", "World"]rilancia can't unsafeBitCast... Indovina che verrà risolto nella prossima versione.
Vincent Guerci,

Potresti trasformare "" nell'operatore utilizzato? '@infix func, (…', quindi scrivi le tue stringhe come "Ciao% @, questo è pi:% .2f", ["tu", M_PI])?
Rick,

@Rick no non puoi, non ,è un operatore personaggio valido, in Swift e nella maggior parte delle lingue. E imo, è meglio usare l' %operatore che esiste già in altre lingue. Vedere developer.apple.com/library/ios/documentation/Swift/Conceptual/…
Vincent Guerci,

8

Swift 4

let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)

let temp: Float = div * 100 let string = String (formato: "% .2f", locale: Locale.current, argomenti: temp) mi sta dando errore. Impossibile convertire il valore del tipo 'Float' nel tipo di argomento previsto '[CVarArg]
Chandni,

devi mettere quel 15.123 in un array per farlo funzionare
Dorian Roy,

3
per me funziona: let string = String (formato: "% .2f", myString)
Grzegorz R. Kulesza

6

Puoi comunque usare NSLog in Swift come in Objective-C solo senza il segno @.

NSLog("%.02f %.02f %.02f", r, g, b)

Modifica: dopo aver lavorato con Swift da un po 'di tempo, vorrei aggiungere anche questa variazione

    var r=1.2
    var g=1.3
    var b=1.4
    NSLog("\(r) \(g) \(b)")

Produzione:

2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4

6

Dettagli

  • Xcode 9.3, Swift 4.1
  • Xcode 10.2.1 (10E1001), Swift 5

Soluzione 1

func arrotondato () -> Double

(5.2).rounded()
// 5.0
(5.5).rounded()
// 6.0
(-5.2).rounded()
// -5.0
(-5.5).rounded()
// -6.0

func arrotondato (_ rule: FloatingPointRoundingRule) -> Double

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

funzione mutating round ()

var x = 5.2
x.round()
// x == 5.0
var y = 5.5
y.round()
// y == 6.0
var z = -5.5
z.round()
// z == -6.0

funzione mutating round (_ rule: FloatingPointRoundingRule)

// Equivalent to the C 'round' function:
var w = 6.5
w.round(.toNearestOrAwayFromZero)
// w == 7.0

// Equivalent to the C 'trunc' function:
var x = 6.5
x.round(.towardZero)
// x == 6.0

// Equivalent to the C 'ceil' function:
var y = 6.5
y.round(.up)
// y == 7.0

// Equivalent to the C 'floor' function:
var z = 6.5
z.round(.down)
// z == 6.0

Soluzione 2

extension Numeric {

    private func _precision(number: NSNumber, formatter: NumberFormatter) -> Self? {
        if  let formatedNumString = formatter.string(from: number),
            let formatedNum = formatter.number(from: formatedNumString) {
                return formatedNum as? Self
        }
        return nil
    }

    private func toNSNumber() -> NSNumber? {
        if let num = self as? NSNumber { return num }
        guard let string = self as? String, let double = Double(string) else { return nil }
        return NSNumber(value: double)
    }

    func precision(_ minimumFractionDigits: Int,
                   roundingMode: NumberFormatter.RoundingMode = NumberFormatter.RoundingMode.halfUp) -> Self? {
        guard let number = toNSNumber() else { return nil }
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = minimumFractionDigits
        formatter.roundingMode = roundingMode
        return _precision(number: number, formatter: formatter)
    }

    func precision(with numberFormatter: NumberFormatter) -> String? {
        guard let number = toNSNumber() else { return nil }
        return numberFormatter.string(from: number)
    }
}

uso

_ = 123.44.precision(2)
_ = 123.44.precision(3, roundingMode: .up)

let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 1
numberFormatter.groupingSeparator = " "
let num = 222.3333
_ = num.precision(2)

Campione completo

func option1<T: Numeric>(value: T, numerFormatter: NumberFormatter? = nil) {
    print("Type: \(type(of: value))")
    print("Original Value: \(value)")
    let value1 = value.precision(2)
    print("value1 = \(value1 != nil ? "\(value1!)" : "nil")")
    let value2 = value.precision(5)
    print("value2 = \(value2 != nil ? "\(value2!)" : "nil")")
    if let value1 = value1, let value2 = value2 {
        print("value1 + value2 = \(value1 + value2)")
    }
    print("")
}

func option2<T: Numeric>(value: T, numberFormatter: NumberFormatter) {
    print("Type: \(type(of: value))")
    print("Original Value: \(value)")
    let value1 = value.precision(with: numberFormatter)
    print("formated value = \(value1 != nil ? "\(value1!)" : "nil")\n")
}

func test(with double: Double) {
    print("===========================\nTest with: \(double)\n")
    let float = Float(double)
    let float32 = Float32(double)
    let float64 = Float64(double)
    let float80 = Float80(double)
    let cgfloat = CGFloat(double)

    // Exapmle 1
    print("-- Option1\n")
    option1(value: double)
    option1(value: float)
    option1(value: float32)
    option1(value: float64)
    option1(value: float80)
    option1(value: cgfloat)

    // Exapmle 2

    let numberFormatter = NumberFormatter()
    numberFormatter.formatterBehavior = .behavior10_4
    numberFormatter.minimumIntegerDigits = 1
    numberFormatter.minimumFractionDigits = 4
    numberFormatter.maximumFractionDigits = 9
    numberFormatter.usesGroupingSeparator = true
    numberFormatter.groupingSeparator = " "
    numberFormatter.groupingSize = 3

    print("-- Option 2\n")
    option2(value: double, numberFormatter: numberFormatter)
    option2(value: float, numberFormatter: numberFormatter)
    option2(value: float32, numberFormatter: numberFormatter)
    option2(value: float64, numberFormatter: numberFormatter)
    option2(value: float80, numberFormatter: numberFormatter)
    option2(value: cgfloat, numberFormatter: numberFormatter)
}

test(with: 123.22)
test(with: 1234567890987654321.0987654321)

Produzione

===========================
Test with: 123.22

-- Option1

Type: Double
Original Value: 123.22
value1 = 123.22
value2 = 123.22
value1 + value2 = 246.44

Type: Float
Original Value: 123.22
value1 = nil
value2 = nil

Type: Float
Original Value: 123.22
value1 = nil
value2 = nil

Type: Double
Original Value: 123.22
value1 = 123.22
value2 = 123.22
value1 + value2 = 246.44

Type: Float80
Original Value: 123.21999999999999886
value1 = nil
value2 = nil

Type: CGFloat
Original Value: 123.22
value1 = 123.22
value2 = 123.22
value1 + value2 = 246.44

-- Option 2

Type: Double
Original Value: 123.22
formatted value = 123.2200

Type: Float
Original Value: 123.22
formatted value = 123.220001221

Type: Float
Original Value: 123.22
formatted value = 123.220001221

Type: Double
Original Value: 123.22
formatted value = 123.2200

Type: Float80
Original Value: 123.21999999999999886
formatted value = nil

Type: CGFloat
Original Value: 123.22
formatted value = 123.2200

===========================
Test with: 1.2345678909876544e+18

-- Option1

Type: Double
Original Value: 1.2345678909876544e+18
value1 = 1.23456789098765e+18
value2 = 1.23456789098765e+18
value1 + value2 = 2.4691357819753e+18

Type: Float
Original Value: 1.234568e+18
value1 = nil
value2 = nil

Type: Float
Original Value: 1.234568e+18
value1 = nil
value2 = nil

Type: Double
Original Value: 1.2345678909876544e+18
value1 = 1.23456789098765e+18
value2 = 1.23456789098765e+18
value1 + value2 = 2.4691357819753e+18

Type: Float80
Original Value: 1234567890987654400.0
value1 = nil
value2 = nil

Type: CGFloat
Original Value: 1.2345678909876544e+18
value1 = 1.23456789098765e+18
value2 = 1.23456789098765e+18
value1 + value2 = 2.4691357819753e+18

-- Option 2

Type: Double
Original Value: 1.2345678909876544e+18
formatted value = 1 234 567 890 987 650 000.0000

Type: Float
Original Value: 1.234568e+18
formatted value = 1 234 567 939 550 610 000.0000

Type: Float
Original Value: 1.234568e+18
formatted value = 1 234 567 939 550 610 000.0000

Type: Double
Original Value: 1.2345678909876544e+18
formatted value = 1 234 567 890 987 650 000.0000

Type: Float80
Original Value: 1234567890987654400.0
formatted value = nil

Type: CGFloat
Original Value: 1.2345678909876544e+18
formatted value = 1 234 567 890 987 650 000.0000

4
extension Double {
  func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
     let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
     return Double(formattedString)!
     }
 }

 1.3333.formatWithDecimalPlaces(2)

3

Le risposte fornite finora che hanno ottenuto il maggior numero di voti si basano sui metodi NSString e richiedono l'importazione di Foundation.

Dopo averlo fatto, comunque accesso a NSLog.

Quindi penso che la risposta alla domanda, se stai chiedendo come continuare a utilizzare NSLog in Swift, è semplicemente:

import Foundation


3
//It will more help, by specify how much decimal Point you want.
let decimalPoint = 2
let floatAmount = 1.10001
let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)

2

qui una soluzione "pura" rapida

 var d = 1.234567
operator infix ~> {}
@infix func ~> (left: Double, right: Int) -> String {
    if right == 0 {
        return "\(Int(left))"
    }
    var k = 1.0
    for i in 1..right+1 {
        k = 10.0 * k
    }
    let n = Double(Int(left*k)) / Double(k)
    return "\(n)"
}
println("\(d~>2)")
println("\(d~>1)")
println("\(d~>0)")

2

Potenza di estensione

extension Double {
    var asNumber:String {
        if self >= 0 {
            var formatter = NSNumberFormatter()
            formatter.numberStyle = .NoStyle
            formatter.percentSymbol = ""
            formatter.maximumFractionDigits = 1
            return "\(formatter.stringFromNumber(self)!)"
        }
        return ""
    }
}

let velocity:Float = 12.32982342034

println("The velocity is \(velocity.toNumber)")

Uscita: la velocità è 12.3


2

meno modo di scrivere:

func fprint(format: String, _ args: CVarArgType...) {
    print(NSString(format: format, arguments: getVaList(args)))
}

1

È inoltre possibile creare un operatore in questo modo

operator infix <- {}

func <- (format: String, args:[CVarArg]) -> String {
    return String(format: format, arguments: args)
}

let str = "%d %.1f" <- [1453, 1.123]

1

Anche con arrotondamento:

extension Float
{
    func format(f: String) -> String
    {
        return NSString(format: "%\(f)f", self)
    }
    mutating func roundTo(f: String)
    {
        self = NSString(format: "%\(f)f", self).floatValue
    }
}

extension Double
{
    func format(f: String) -> String
    {
        return NSString(format: "%\(f)f", self)
    }
    mutating func roundTo(f: String)
    {
        self = NSString(format: "%\(f)f", self).doubleValue
    }
}

x = 0.90695652173913
x.roundTo(".2")
println(x) //0.91

1

utilizzare il metodo seguente

let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)

println(output)

1

Una versione dell'operatore ruby ​​/ python% di Vincent Guerci, aggiornata per Swift 2.1:

func %(format:String, args:[CVarArgType]) -> String {
  return String(format:format, arguments:args)
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]

1

Un sacco di buone risposte sopra, ma a volte uno schema è più appropriato del tipo "% .3f" di gobbledygook. Ecco la mia interpretazione usando un NumberFormatter in Swift 3.

extension Double {
  func format(_ pattern: String) -> String {
    let formatter = NumberFormatter()
    formatter.format = pattern
    return formatter.string(from: NSNumber(value: self))!
  }    
}

let n1 = 0.350, n2 = 0.355
print(n1.format("0.00#")) // 0.35
print(n2.format("0.00#")) // 0.355

Qui volevo che venissero mostrati sempre 2 decimali, ma il terzo solo se non era zero.


1

Aggiornamento Swift 4 Xcode 10

extension Double {
    var asNumber:String {
        if self >= 0 {
            let formatter = NumberFormatter()
            formatter.numberStyle = .none
            formatter.percentSymbol = ""
            formatter.maximumFractionDigits = 2
            return "\(formatter.string(from: NSNumber(value: self)) ?? "")"
        }
        return ""
    }
}

1

Che dire delle estensioni sui tipi Double e CGFloat:

extension Double {

   func formatted(_ decimalPlaces: Int?) -> String {
      let theDecimalPlaces : Int
      if decimalPlaces != nil {
         theDecimalPlaces = decimalPlaces!
      }
      else {
         theDecimalPlaces = 2
      }
      let theNumberFormatter = NumberFormatter()
      theNumberFormatter.formatterBehavior = .behavior10_4
      theNumberFormatter.minimumIntegerDigits = 1
      theNumberFormatter.minimumFractionDigits = 1
      theNumberFormatter.maximumFractionDigits = theDecimalPlaces
      theNumberFormatter.usesGroupingSeparator = true
      theNumberFormatter.groupingSeparator = " "
      theNumberFormatter.groupingSize = 3

      if let theResult = theNumberFormatter.string(from: NSNumber(value:self)) {
         return theResult
      }
      else {
         return "\(self)"
      }
   }
}

Uso:

let aNumber: Double = 112465848348508.458758344
Swift.print("The number: \(aNumber.formatted(2))")

stampe: 112 465 848 348 508,46


0
@infix func ^(left:Double, right: Int) -> NSNumber {
    let nf = NSNumberFormatter()
    nf.maximumSignificantDigits = Int(right)
    return  nf.numberFromString(nf.stringFromNumber(left))
}


let r = 0.52264
let g = 0.22643
let b = 0.94837

println("this is a color: \(r^3) \(g^3) \(b^3)")

// this is a color: 0.523 0.226 0.948

0

Non conosco due cifre decimali, ma ecco come è possibile stampare i float con zero cifre decimali, quindi immagino che possano essere 2 posizioni, 3, posizioni ... (Nota: è necessario convertire CGFloat in Double per passare su String (formato :) o vedrà un valore pari a zero)

func logRect(r: CGRect, _ title: String = "") {
    println(String(format: "[ (%.0f, %.0f), (%.0f, %.0f) ] %@",
        Double(r.origin.x), Double(r.origin.y), Double(r.size.width), Double(r.size.height), title))
}

0

Esempio Swift2: larghezza dello schermo del dispositivo iOS formattando il Float rimuovendo il decimale

print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))

-1

@Christian Dietrich:

invece di:

var k = 1.0
    for i in 1...right+1 {
        k = 10.0 * k
    }
let n = Double(Int(left*k)) / Double(k)
return "\(n)"

potrebbe anche essere:

let k = pow(10.0, Double(right))
let n = Double(Int(left*k)) / k
return "\(n)"

[correzione:] Ci scusiamo per la confusione * - Ovviamente funziona con i doppi. Penso, molto pratico (se si desidera che le cifre siano arrotondate, non tagliate) sarebbe qualcosa del genere:

infix operator ~> {}
func ~> (left: Double, right: Int) -> Double {
    if right <= 0 {
        return round(left)
    }
    let k = pow(10.0, Double(right))
    return round(left*k) / k
}

Solo per Float, sostituisci semplicemente Double con Float, pow con powf e round con roundf.
Aggiornamento: ho scoperto che è più pratico utilizzare il tipo restituito Double anziché String. Funziona allo stesso modo per l'output String, ovvero:

println("Pi is roughly \(3.1415926 ~> 3)")

stampe: Pi è all'incirca 3.142,
quindi puoi usarlo allo stesso modo per Strings (puoi anche ancora scrivere: println (d ~> 2)), ma puoi anche usarlo per arrotondare i valori direttamente, cioè:

d = Double(slider.value) ~> 2

o qualunque cosa tu abbia bisogno ...


Questo ovviamente è destinato ad essere un commento, capisco che hai bisogno di più spazio per fare un punto, ed è prezioso, ma se hai intenzione di scriverlo come una risposta a tutti gli effetti lo rendi utile da solo, indipendentemente; potresti aggiungere il codice completo, ad esempio, e quindi un'osservazione e riconoscere a Christian.
Jaime Gómez,

@Jaime Gómez: Non mi è permesso commentare la risposta sopra. Ma comunque, ho avuto qualche falsa interpretazione * in esso. Non so, se vale la pena di essere conservato o deve essere eliminato. Naturalmente questo può essere usato in modo simile solo per arrotondare (senza conversione di stringhe) e può essere facilmente tradotto in altri linguaggi di programmazione. * Supponevo che con Double venisse arrotondato a circa 8 cifre, il che ovviamente era un errore, perché l'ho arrotondato con Float e l'ho convertito in Double accidentalmente.
Stuepfnick,

PS: Preferirei usare metodi simili più per l'arrotondamento in generale, non per l'output String, quindi restituisci il tipo Double (e metodo normale?) Sidenote : Se arrotondi un Float in quel modo (cioè da uno Slider) e il risultato è String andrà bene, come "0.1", ma se converti quel Float in Double e poi in String * sarà: "0.100000001490116", poiché Float non è in grado di memorizzare esattamente 0.1, solo molto vicino. Immagino sia lo stesso con Double, solo con doppia precisione ;) Quindi converti sempre in Double prima dell'arrotondamento, quindi sarà il più esatto possibile e convertirà anche in String.
Stuepfnick

PPS: Certo, con Return Type Double, a volte è un po 'diverso, cioè se devi impostare un testo per l'etichetta, devi scrivere: myLabel.text = "\ (d ~> 2)" invece di solo: myLabel. text = d ~> 2 , ma penso ancora, la funzione è più pratica in questo modo. (ovviamente tutti possono fare, quello che vogliono, solo i miei pensieri ...)
Stuepfnick

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.