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
we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.
Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
let b = 2.1
println(String(format:"%.02f", b))
gives the string "2.10" in my playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With