2015-05-22 10 views
18

sto usando SwiftNSNumberFormatter PercentStyle decimali

let myDouble = 8.5 as Double 

let percentFormatter   = NSNumberFormatter() 
percentFormatter.numberStyle = NSNumberFormatterStyle.PercentStyle 
percentFormatter.multiplier  = 1.00 

let myString = percentFormatter.stringFromNumber(myDouble)! 

println(myString) 

uscite 8% e non dell'8,5%, come potrei farlo uscita 8,5%? (Ma solo fino a 2 cifre decimali)

risposta

27

Per impostare il numero di cifre decimali utilizzare:

percentFormatter.minimumFractionDigits = 1 
percentFormatter.maximumFractionDigits = 1 

Set minimo e massimo alle vostre esigenze. Dovrebbe essere auto-esplicativo.

+2

e fino a 2 cifre decimali, imposta 'percentFormatter.maximumFractionDigits' su' 2'. '8.5' verrà visualizzato come' 8.5', ma '8.534' verrà visualizzato come' 8.53'. –

4

Con Swift 3, NumberFormatter ha una proprietà di istanza denominata minimumFractionDigits. minimumFractionDigits ha la seguente dichiarazione:

var minimumFractionDigits: Int { get set } 

Il numero minimo di cifre dopo il separatore decimale ammesso come ingresso e uscita dal ricevitore.


NumberFormatter ha anche una proprietà di istanza denominata maximumFractionDigits. maximumFractionDigits ha la seguente dichiarazione:

var maximumFractionDigits: Int { get set } 

Il numero massimo di cifre dopo il separatore decimale ammesso come ingresso e uscita dal ricevitore.


Il seguente codice di giochi mostra come utilizzare minimumFractionDigits e maximumFractionDigits al fine di impostare il numero di cifre dopo il separatore decimale quando si utilizza NumberFormatter:

import Foundation 

let percentFormatter = NumberFormatter() 
percentFormatter.numberStyle = NumberFormatter.Style.percent 
percentFormatter.multiplier = 1 
percentFormatter.minimumFractionDigits = 1 
percentFormatter.maximumFractionDigits = 2 

let myDouble1: Double = 8 
let myString1 = percentFormatter.string(for: myDouble1) 
//let myString1 = percentFormatter.string(from: NSNumber(value: myDouble1)) // also works 
print(String(describing: myString1)) // Optional("8.0%") 

let myDouble2 = 8.5 
let myString2 = percentFormatter.string(for: myDouble2) 
print(String(describing: myString2)) // Optional("8.5%") 

let myDouble3 = 8.5786 
let myString3 = percentFormatter.string(for: myDouble3) 
print(String(describing: myString3)) // Optional("8.58%")