I am writing an app in swift
and have used the below code . So my output is rounded up to 2 decimal places as expected.
This is working well. However if the result is less than 2 decimal places it shows only 1 digit. This is the most basic example but I have results that could either be a whole number or 10 decimal places. I want them all to show as .xx
1.2345 => 1.23
1.1 => 1.1
How do I get the results to always display 2 decimal places regardless of the number of digits after decimal point ?
E.g: 1.1 => 1.10
I have searched extensively but the answer eludes me. This is the code that I have tried so far :
@IBOutlet var odds: UITextField!
@IBOutlet var oddsLabel: UILabel!
var enteredOdds = NSString(string: odds.text).doubleValue
var numberOfPlaces = 2.0
var multiplier = pow(10.0, numberOfPlaces)
var enteredOddsRounded = round(enteredOdds * multiplier) / multiplier
oddsLabel.text = "\(enteredOddsRounded)"
println("\(enteredOddsRounded)")
Thanks for the comments. I have amended as follows:
@IBOutlet var odds: UITextField!
@IBOutlet var oddsLabel: UILabel!
var enteredOdds = NSString(string: odds.text).doubleValue
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
for identifier in ["en_UK", "eu_US"] {
formatter.locale = NSLocale(localeIdentifier: identifier)
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
}
oddsLabel.text = formatter.stringFromNumber(enteredOdds)
It allowed me to lose a lot of code as it does the rounding and decimal places for me while also including currency as a bonus.
Thile this has worked for all the fields where I actually did need currency to be displayed, The above value 'oddsLabel.text' is not actually currency and so only resolved the rounding and decimal places.
How do I amend the above so it can take into account fields with and/or without currency. Hopefully without having re replicate the code again?
Thanks again for all the quick replies.
Frank