8

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

1
  • Create a new formatter instance for every field. You don't have to replicate, just create functions for the common things.
    – Sulthan
    Commented Apr 1, 2015 at 21:30

5 Answers 5

23
let b = 2.1
println(String(format:"%.02f", b))

gives the string "2.10" in my playground.

18

What you have used is called a "naive" implementation. It works mostly but it has some minor problems and some hidden problems. One of the hidden problems is that you completely ignore user locale - most european languages use comma as a decimal separator and not a point.

To handle the problem of decimal number to string conversion (and viceversa), most programming languages provide dedicated API. In Cocoa/CocoaTouch there is NumberFormatter.

Example:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
oddsLabel.text = formatter.string(for: enteredOdds)

Note the rounding is done for you.

2
  • Thanks Sulthan, I implemented a version of this but including locale for currency using the link from John below. Commented Apr 1, 2015 at 17:39
  • awesome solution Commented Sep 21, 2017 at 16:20
4

Maybe you are looking for NSNumberFormatter:

let nf = NSNumberFormatter()
nf.minimumFractionDigits = 2
nf.stringFromNumber(enteredOddsRounded)
2

Extension to set minimum fraction digits:

   extension String {
        func setMinTailingDigits() -> String {
            let formatter = NumberFormatter()
            formatter.minimumFractionDigits = 2
            return formatter.string(from: Double(self)! as NSNumber)!
        }
    }
1
oddsLabel.text = (NSString(format:"%.2f", enteredOddsRounded))

This is what i use in some instances

there is also an option to use NSNumberFormatter where you can add commas as well

here is a tutorial http://nshipster.com/nsformatter/

1
  • Thanks John, I used the link to find a part solution similar to Sulthans. Though now I need to figure out how to recognise if the output should be currency or now. Commented Apr 1, 2015 at 17:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.