1 Reply
      Latest reply: Sep 5, 2016 2:51 AM by eskimo RSS
      Dan_Scott_ZA Level 1 Level 1 (0 points)

        Hi guys, I'm a complete noob when it comes to Swift but I would appreciate any help.

        The input value is set to be a float, but when displaying the calc results, I need it to be decimal style AND rounded up to the nearest 0.01.

         

        It currently rounds off to the nearest 3 decimals, but I need it to be two decimals.

         

        My code currently:

         

        func roundUp(number: Float, toNearest: Float) -> Float {

                return ceil(number / toNearest) * toNearest

            }

         

         

        let income = grossin - LocalGrossIncomeArray[5] + IntrestSAArray[3]  - LocalGrossIncomeArray[9] - LocalGrossIncomeArray[8]

         

        roundUp(income, toNearest: 0.1)

         

            print("Income Round up value = \(income)")

         

        roundUp(grossin, toNearest: 0.1)

         

        print("grossin Round up value = \(grossin)")

         

        let numberFormatterIncome = NSNumberFormatter()

            numberFormatterIncome.numberStyle = .DecimalStyle

            IncomeLbl.text = "R "

            IncomeLbl.text = IncomeLbl.text! + numberFormatterIncome.stringFromNumber(income)!

         

        let numberFormatter = NSNumberFormatter()

            numberFormatter.numberStyle = .DecimalStyle

        GrossIncome.text = "R "

        GrossIncome.text = GrossIncome.text! + numberFormatter.stringFromNumber(Double(grossin))!

        • Re: Rounding of floats to 2 decimals
          eskimo Apple Staff Apple Staff (6,665 points)

          It sounds like you’re working with currencies.  If so, you should check out NSDecimalNumber, which is a fixed point number format.  Mixing floating point and currencies will generally end badly because binary floating point is unable to represent simple decimal values (like 0.1) without losing accuracy.

          With regards NSNumberFormatter, if you want to control how many fractional digits it shows you can do that using the minimumFractionDigits and maximumFractionDigits properties.  For example:

          import Foundation
          
          let nf = NSNumberFormatter()
          nf.numberStyle = .DecimalStyle
          nf.minimumFractionDigits = 3
          nf.maximumFractionDigits = 3
          print(nf.stringFromNumber(0.123)!)  // -> “0.123”
          

          Share and Enjoy

          Quinn “The Eskimo!”
          Apple Developer Relations, Developer Technical Support, Core OS/Hardware
          let myEmail = "eskimo" + "1" + "@apple.com"