I am writing an application in swift and used the code below. Thus, my result is rounded to two decimal places, as expected.
It works well. However, if the result is less than 2 decimal places, it only shows 1 digit. This is the most basic example, but I have results that can be an integer or 10 decimal places. I want them all to display as .xx
1.2345 => 1.23 1.1 => 1.1
How do I get results to always show 2 decimal places regardless of the number of digits after the decimal point?
For example: 1.1 => 1.10
I searched many times, but the answer eluded me. This is the code I've 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 made the changes 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)
This allowed me to lose a lot of code, since it rounds off and decimal numbers for me, and also includes currency as a bonus.
Thile, this worked for all fields where I really needed a currency to display. The above value of "oddsLabel.text" is not really a currency and therefore allows rounding and decimal places.
How to change the above so that it can take into account fields with and / or without currency. Hopefully not repeating the code again?
Thanks again for all the quick answers.
Franc