Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forcing a number to be displayed with 2 decimal places using swift

Tags:

text

swift

I have a lot of code very similar to this.

//Gross Total
    var gt:Float64 = tp01 + tp02 + tp03 + tp04 + tp05 + tat + ntat
    GrossTotal.text = "\(gt)"

Where I display numbers in a label. This code works fine. I would like to know how to force the number being displayed to always have a value with exactly 2 decimal places. Please only swift code. thank you

like image 537
ElectricTiger Avatar asked Oct 16 '25 18:10

ElectricTiger


2 Answers

The Swift String type has an initializer that takes a format string: String(format:args:...)

Your code might look like this: GrossTotal.text = String(format: "%.2f", gt)

EDIT: I had an "@" in front of the string, which is an Objective-C habit. EDIT: Typing error resolved.

like image 148
Duncan C Avatar answered Oct 18 '25 12:10

Duncan C


update: Xcode 10.2 • Swift 5

You can use NumberFormatter to format your string as desired and round it up or down as follow:

extension Formatter {
    static let number = NumberFormatter() 
}

extension BinaryFloatingPoint {
    func fratcionDigitis(_ n: Int, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
        Formatter.number.roundingMode = roundingMode
        Formatter.number.maximumFractionDigits = n
        Formatter.number.minimumFractionDigits = n
        return Formatter.number.string(for: self) ?? ""
    }
}

let tp01 = 3.3232
let tp02 = 1.5673
let tp03 = 1.9764
let tp04 = 2.0986
let tp05 = 5.5557
let tat  = 2.7448
let ntat = 2.2339

let gt: Float64 = tp01 + tp02 + tp03 + tp04 + tp05 + tat + ntat   // 19.4999

let rounded = gt.fratcionDigitis(2)                        // "19.50"
let roundDown = gt.fratcionDigitis(2, roundingMode: .down) // "19.49"
let roundUp = gt.fratcionDigitis(2, roundingMode: .up)     // "19.50"

Or as I mentioned in my comment you can just use String(format:)

String(format: "%.2f", 2.0)
like image 33
Leo Dabus Avatar answered Oct 18 '25 12:10

Leo Dabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!