545

Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)

With totalWorkTime being an NSTimeInterval (double) in second.

totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039......

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

2

36 Answers 36

526

You can use Swift's round function to accomplish this.

To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

let x = 1.23556789
let y = Double(round(1000 * x) / 1000)
print(y) /// 1.236

Unlike any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double.

Regarding the comments that it sometimes does not work, please read this: What Every Programmer Should Know About Floating-Point Arithmetic

9
  • 1
    For some reasons it doesn't help.. I am using this in the following case TransformOf<Double, String>(fromJSON: {Double(round(($0! as NSString).doubleValue * 100)/100)}, toJSON: {"($0)"})
    – Fawkes
    Jul 30, 2015 at 22:50
  • 41
    Doesn't work for me in playground: let rate = 9.94999999999; Double(round(rate * 100) / 100); Output: 9.94999999999, 9.949999999999999 Only works for print but how can I assign it to variable? May 5, 2016 at 8:53
  • 1
    You should use Decimal for this, not plain Doubles.
    – csotiriou
    Dec 12, 2016 at 16:08
  • 34
    "What Every Computer Scientist Should Know About Floating-Point Arithmetic" is 73 pages long. What's the TL;DR on that? :)
    – JaredH
    Apr 14, 2018 at 21:45
  • 2
    @HardikDG I don't remember, sorry :-) Oct 4, 2018 at 10:59
493

Extension for Swift 2

A more general solution is the following extension, which works with Swift 2 & iOS 9:

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}


Extension for Swift 3

In Swift 3 round is replaced by rounded:

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}


Example which returns Double rounded to 4 decimal places:

let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version
11
  • 32
    The nature of Swift's Double appears to be that it can be imprecise – because of the way it's stored/accessed in binary, even using this rounding function will not return a number rounded to 3 decimal places: e.g., round(8.46 * pow(10.0, 3.0)) / pow(10.0, 3.0) returns 8.460000000000001. Doing the same with Float, at least in this scenario, does in fact seem to work: round(Float(8.46) * pow(10.0, 3.0)) / pow(10.0, 3.0) yields 8.46. Just something worth noting. Jul 7, 2016 at 21:51
  • 3
    Unfortunately, this no longer works in Swift 3, I am getting this error No '*' candidates produce the expected contextual result type 'FloatingPointRoundingRule'
    – koen
    Aug 20, 2016 at 19:44
  • 3
    I updated the solution and added an extension for Swift 3.
    – Sebastian
    Aug 22, 2016 at 10:26
  • 3
    To be more swift 3... you should change for func rounded(toPlaces places: Int) -> Double
    – FouZ
    Sep 7, 2016 at 13:11
  • 3
    @BenSaufley But it also does not work if you enter 98.68. In this case, I get 98.6800003 Dec 21, 2016 at 8:31
483

How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?

To round totalWorkTimeInHours to 3 digits for printing, use the String constructor which takes a format string:

print(String(format: "%.3f", totalWorkTimeInHours))
12
  • 36
    That's truncation, not rounding
    – Eyeball
    Dec 7, 2014 at 8:10
  • 49
    @Eyeball: Actually, it DOES round. It is the same behaviour as the C printf functionality, which rounds to the requested digits. So String(format: "%.3f", 1.23489) prints 1.235
    – zisoft
    Dec 7, 2014 at 8:30
  • 9
    The original poster is looking for a numeric value to use, not a string to display.
    – pr1001
    Feb 16, 2016 at 17:28
  • 33
    @pr1001, perhaps so, but that wasn't clear at the time and 46 others have found my answer useful. Stack Overflow is more than just helping the OP.
    – vacawama
    Feb 16, 2016 at 17:44
  • 4
    odd, this is returning 0.00 every time.
    – Eric H
    Jun 23, 2016 at 23:18
378

With Swift 5, according to your needs, you can choose one of the 9 following styles in order to have a rounded result from a Double.


#1. Using FloatingPoint rounded() method

In the simplest case, you may use the Double rounded() method.

let roundedValue1 = (0.6844 * 1000).rounded() / 1000
let roundedValue2 = (0.6849 * 1000).rounded() / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#2. Using FloatingPoint rounded(_:) method

let roundedValue1 = (0.6844 * 1000).rounded(.toNearestOrEven) / 1000
let roundedValue2 = (0.6849 * 1000).rounded(.toNearestOrEven) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#3. Using Darwin round function

Foundation offers a round function via Darwin.

import Foundation

let roundedValue1 = round(0.6844 * 1000) / 1000
let roundedValue2 = round(0.6849 * 1000) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#4. Using a Double extension custom method built with Darwin round and pow functions

If you want to repeat the previous operation many times, refactoring your code can be a good idea.

import Foundation

extension Double {
    func roundToDecimal(_ fractionDigits: Int) -> Double {
        let multiplier = pow(10, Double(fractionDigits))
        return Darwin.round(self * multiplier) / multiplier
    }
}

let roundedValue1 = 0.6844.roundToDecimal(3)
let roundedValue2 = 0.6849.roundToDecimal(3)
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#5. Using NSDecimalNumber rounding(accordingToBehavior:) method

If needed, NSDecimalNumber offers a verbose but powerful solution for rounding decimal numbers.

import Foundation

let scale: Int16 = 3

let behavior = NSDecimalNumberHandler(roundingMode: .plain, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)

let roundedValue1 = NSDecimalNumber(value: 0.6844).rounding(accordingToBehavior: behavior)
let roundedValue2 = NSDecimalNumber(value: 0.6849).rounding(accordingToBehavior: behavior)

print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#6. Using NSDecimalRound(_:_:_:_:) function

import Foundation

let scale = 3

var value1 = Decimal(0.6844)
var value2 = Decimal(0.6849)

var roundedValue1 = Decimal()
var roundedValue2 = Decimal()

NSDecimalRound(&roundedValue1, &value1, scale, NSDecimalNumber.RoundingMode.plain)
NSDecimalRound(&roundedValue2, &value2, scale, NSDecimalNumber.RoundingMode.plain)

print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#7. Using NSString init(format:arguments:) initializer

If you want to return a NSString from your rounding operation, using NSString initializer is a simple but efficient solution.

import Foundation

let roundedValue1 = NSString(format: "%.3f", 0.6844)
let roundedValue2 = NSString(format: "%.3f", 0.6849)
print(roundedValue1) // prints 0.684
print(roundedValue2) // prints 0.685

#8. Using String init(format:_:) initializer

Swift’s String type is bridged with Foundation’s NSString class. Therefore, you can use the following code in order to return a String from your rounding operation:

import Foundation

let roundedValue1 = String(format: "%.3f", 0.6844)
let roundedValue2 = String(format: "%.3f", 0.6849)
print(roundedValue1) // prints 0.684
print(roundedValue2) // prints 0.685

#9. Using NumberFormatter

If you expect to get a String? from your rounding operation, NumberFormatter offers a highly customizable solution.

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.roundingMode = NumberFormatter.RoundingMode.halfUp
formatter.maximumFractionDigits = 3

let roundedValue1 = formatter.string(from: 0.6844)
let roundedValue2 = formatter.string(from: 0.6849)
print(String(describing: roundedValue1)) // prints Optional("0.684")
print(String(describing: roundedValue2)) // prints Optional("0.685")
8
  • 3
    Great answer. I might suggest on #5 that you might consider using Decimal, which is toll free bridged to NSDecimalNumber. Decimal is Swift’s native type and offers more elegant support for native operators like +, -, etc.
    – Rob
    Feb 5, 2018 at 17:40
  • 1
    Using #9 choice will guarantee that you will expect the fixed fraction (number of precision digits), lets say decimal number 43.12345 and fraction = 6, you get 43.123450 Apr 20, 2018 at 17:11
  • 1
    @ImanouPetit Thank you for posting this. I can nuke a couple of extensions.
    – Adrian
    Jun 3, 2018 at 0:35
  • 6
    I am sad NumberFormatter is the last option while it should be the first for presenting numbers to users. No other method generates properly localized numbers.
    – Sulthan
    Jan 20, 2019 at 14:43
  • 1
    The extremely customizable nature of NumberFormatter did it for me! Glad I read all the way to the bottom of your answer.
    – Carl Smith
    Apr 9, 2021 at 9:26
203

In Swift 5.7 and Xcode 14:

let pi: Double = 3.14159265358979
String(format:"%.2f", pi)

Example:

Rounding a double value

PS.: It still the same since Swift 2.0 and Xcode 7.2
3
  • Looking at your code I made a small like this and it works fine: extension Float { var toString: String { return String(format: "%.2f", self) } }
    – Sanjeevcn
    Apr 18, 2022 at 6:50
  • I used it on a string var that goes on a long string expression to be displayed on SwiftUI Text view. Lot of thanks Oct 28, 2022 at 0:27
  • Why do you keep updating the version numbers? The two lines of code you posted have been valid for many years and are not specific to the current versions shown.
    – HangarRash
    Nov 1 at 15:51
61

This is a fully worked code

Swift 3.0/4.0/5.0 , Xcode 9.0 GM/9.2 and above

let doubleValue : Double = 123.32565254455
self.lblValue.text = String(format:"%.f", doubleValue)
print(self.lblValue.text)

output - 123

let doubleValue : Double = 123.32565254455
self.lblValue_1.text = String(format:"%.1f", doubleValue)
print(self.lblValue_1.text)

output - 123.3

let doubleValue : Double = 123.32565254455
self.lblValue_2.text = String(format:"%.2f", doubleValue)
print(self.lblValue_2.text)

output - 123.33

let doubleValue : Double = 123.32565254455
self.lblValue_3.text = String(format:"%.3f", doubleValue)
print(self.lblValue_3.text)

output - 123.326

2
  • 2
    one line?, seems like 3 lines ;) Sep 27, 2017 at 12:36
  • you can't calculate things using strings, I don't think its a correct answer because its only for displaying.
    – JBarros35
    Mar 10, 2020 at 12:37
35

Building on Yogi's answer, here's a Swift function that does the job:

func roundToPlaces(value:Double, places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return round(value * divisor) / divisor
}

As extension with rounding rule:

extension Double {
    /// - returns: Rounded value with specific round rule and precision
    func roundToPlaces(_ rule: FloatingPointRoundingRule? = . toNearestOrEven, precision: Int) -> Double {
        let divisor = pow(10.0, Double(precision))
        return (self * divisor).rounded(rule) / divisor
    }
}

print(0.123456.roundToPlaces(.down, precision: 4)) // 0.1234
print(0.123456.roundToPlaces(.up, precision: 4)) // 0.1235
0
31

In Swift 3.0 and Xcode 8.0:

extension Double {
    func roundTo(places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

Use this extension like so:

let doubleValue = 3.567
let roundedValue = doubleValue.roundTo(places: 2)
print(roundedValue) // prints 3.56
0
26

Swift 4, Xcode 10

yourLabel.text =  String(format:"%.2f", yourDecimalValue)
2
  • 2
    I didn't downvote, but I think the reason might be because this is returning a string representation of a number, not the number. Which is fine if that's all you need but you might want the number itself rounded off for further use. The OP did say "when I print" so I do think this is an acceptable, easy, and clean solution in this case.
    – Ben Stahl
    Feb 19, 2019 at 21:07
  • 1
    Perfect. One line solution. I just needed to show decimal values as Strings in my labels.
    – zeeshan
    Mar 6, 2019 at 19:40
20

The code for specific digits after decimals is:

var a = 1.543240952039
var roundedString = String(format: "%.3f", a)

Here the %.3f tells the swift to make this number rounded to 3 decimal places.and if you want double number, you may use this code:

// String to Double

var roundedString = Double(String(format: "%.3f", b))

0
17

Use the built in Foundation Darwin library

SWIFT 3

extension Double {
    func round(to places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return Darwin.round(self * divisor) / divisor
    }
}

Usage:

let number:Double = 12.987654321
print(number.round(to: 3)) 

Outputs: 12.988

17

There are two separate questions:

  1. The accurate internal representation of rounded decimal value

    If you want to round Double values, you might want to use Swift Decimal so you don't introduce any errors that can crop up when trying to math with these rounded values. If you use Decimal, it can accurately represent decimal values of that rounded floating point value.

    So you can do:

    extension Double {
        /// Convert `Double` to `Decimal`, rounding it to `scale` decimal places.
        ///
        /// - Parameters:
        ///   - scale: How many decimal places to round to. Defaults to `0`.
        ///   - mode:  The preferred rounding mode. Defaults to `.plain`.
        /// - Returns: The rounded `Decimal` value.
    
        func roundedDecimal(to scale: Int = 0, mode: NSDecimalNumber.RoundingMode = .plain) -> Decimal {
            var decimalValue = Decimal(self)
            var result = Decimal()
            NSDecimalRound(&result, &decimalValue, scale, mode)
            return result
        }
    }
    

    Then, you can get the rounded Decimal value like so:

    let foo = 1427.3000000002
    let value = foo.roundedDecimal(to: 2)          // results in 1427.30
    

    This concept of using Decimal for the value is essential in financial apps where you do not just want to ignore/hide errors introduced with calculations of binary floating point numbers.

  2. The string representation of a rounded value in the UI

    If you want to display it with a specified number of decimal places (as well as localize the string for the user’s current locale), you can use a NumberFormatter:

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 2
    formatter.minimumFractionDigits = 2
    formatter.numberStyle = .decimal
    
    if let string = formatter.string(for: value) {
        print(string)                              // correctly results in “1,427.30” in US; “1.427,30” in Germany
    }
    

    Note, this use of a formatter (notably the localization) is useful both with Decimal values and binary floating point numbers.

    Also note that the above applies to AppKit/UIKit. In SwiftUI, you can use the “specifier” and it will localize and format the string for you:

    Text("Value is \(value, specifier: "%0.2f")") // again, results in “1,427.30” in US; “1.427,30” in Germany
    
5
  • 3
    The best answer so far.
    – Codetard
    Sep 23, 2018 at 11:29
  • (4.81).roundedDecimal(to: 2, mode: .down) will return 4.8 instead of 4.81, use Decimal(string: self.description)! for a precise decimalValue Nov 22, 2018 at 20:16
  • 3
    @vk.edward.li - Yes, one should be wary about rounding decimals up/down, because values like 4.81 simply can not be accurately represented with Double (it becomes 4.8099999999999996). But I'd advise against using description (as the rounding it employs is not documented and is subject to change). If you really want to be doing decimal-accurate math, you should avoid Double entirely and should instead use Decimal directly (e.g. Decimal(sign: .plus, exponent: -2, significand: 481) or Decimal(string: "4.81"). But don't use description.
    – Rob
    Nov 26, 2018 at 1:08
  • @Rob usually it is impossible to get the string value of "4.81" if it is stored as Double, so you have to use self.description (a modified Grisu2 algorithm) to fix the precision which is already lost Dec 10, 2018 at 11:54
  • 1
    I understand your point. I just disagree with your solution. The rounding behavior of description method is neither documented nor guaranteed. Plus, it’s not localized. IMHO, it’s a mistake to use description for anything other than logging purposes. I’d either use Decimal throughout, avoiding using Double entirely, or just use a different rounding mode. Or, if you must, use your own localized method that uses Grisu-style algorithm (but that seems unnecessary when you know to how many decimal places you want to round). But I’d avoid relying on this ancillary behavior of description.
    – Rob
    Dec 12, 2018 at 16:16
13

A handy way can be the use of extension of type Double

extension Double {
    var roundTo2f: Double {return Double(round(100 *self)/100)  }
    var roundTo3f: Double {return Double(round(1000*self)/1000) }
}

Usage:

let regularPie:  Double = 3.14159
var smallerPie:  Double = regularPie.roundTo3f  // results 3.142
var smallestPie: Double = regularPie.roundTo2f  // results 3.14
0
12

This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.

let numberFormatter: NSNumberFormatter = {
    let nf = NSNumberFormatter()
    nf.numberStyle = .DecimalStyle
    nf.minimumFractionDigits = 0
    nf.maximumFractionDigits = 1
    return nf
}()

Suppose your variable you want to print is

var printVar = 3.567

This will make sure it is returned in the desired format:

numberFormatter.StringFromNumber(printVar)

The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.

1
  • 1
    A quick note that any formatter is rather expensive programmatically, making it ill-advised for tasks that need to be performed quickly or repetitively. Aug 7, 2017 at 20:13
10

Either:

  1. Using String(format:):

    • Typecast Double to String with %.3f format specifier and then back to Double

      Double(String(format: "%.3f", 10.123546789))!
      
    • Or extend Double to handle N-Decimal places:

      extension Double {
          func rounded(toDecimalPlaces n: Int) -> Double {
              return Double(String(format: "%.\(n)f", self))!
          }
      }
      
  2. By calculation

    • multiply with 10^3, round it and then divide by 10^3...

      (1000 * 10.123546789).rounded()/1000
      
    • Or extend Double to handle N-Decimal places:

      extension Double {    
          func rounded(toDecimalPlaces n: Int) -> Double {
              let multiplier = pow(10, Double(n))
              return (multiplier * self).rounded()/multiplier
          }
      }
      
8

I would use

print(String(format: "%.3f", totalWorkTimeInHours))

and change .3f to any number of decimal numbers you need

1
  • He wanted to print with 3 digits, not to get it in NSTimeInterval Nov 1, 2016 at 18:28
8

This is more flexible algorithm of rounding to N significant digits

Swift 3 solution

extension Double {
// Rounds the double to 'places' significant digits
  func roundTo(places:Int) -> Double {
    guard self != 0.0 else {
        return 0
    }
    let divisor = pow(10.0, Double(places) - ceil(log10(fabs(self))))
    return (self * divisor).rounded() / divisor
  }
}


// Double(0.123456789).roundTo(places: 2) = 0.12
// Double(1.23456789).roundTo(places: 2) = 1.2
// Double(1234.56789).roundTo(places: 2) = 1200
8

round a double value to x number of decimal
NO. of digits after decimal

var x = 1.5657676754
var y = (x*10000).rounded()/10000
print(y)  // 1.5658 

var x = 1.5657676754 
var y = (x*100).rounded()/100
print(y)  // 1.57 

var x = 1.5657676754
var y = (x*10).rounded()/10
print(y)  // 1.6
3
  • What is going on this code? What do the three examples demonstrate?
    – rene
    Aug 26, 2017 at 8:01
  • 1
    Code only answers are not helpful, please try to explain what each of these examples does. Aug 26, 2017 at 9:03
  • This code works, but leaves a string of zeros at the end... May 24 at 16:53
8

For ease to use, I created an extension:

extension Double {
    var threeDigits: Double {
        return (self * 1000).rounded(.toNearestOrEven) / 1000
    }
    
    var twoDigits: Double {
        return (self * 100).rounded(.toNearestOrEven) / 100
    }
    
    var oneDigit: Double {
        return (self * 10).rounded(.toNearestOrEven) / 10
    }
}

var myDouble = 0.12345
print(myDouble.threeDigits)
print(myDouble.twoDigits)
print(myDouble.oneDigit)

The print results are:

0.123
0.12
0.1

Thanks for the inspiration of other answers!

7

The best way to format a double property is to use the Apple predefined methods.

mutating func round(_ rule: FloatingPointRoundingRule)

FloatingPointRoundingRule is a enum which has following possibilities

Enumeration Cases:

case awayFromZero Round to the closest allowed value whose magnitude is greater than or equal to that of the source.

case down Round to the closest allowed value that is less than or equal to the source.

case toNearestOrAwayFromZero Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.

case toNearestOrEven Round to the closest allowed value; if two values are equally close, the even one is chosen.

case towardZero Round to the closest allowed value whose magnitude is less than or equal to that of the source.

case up Round to the closest allowed value that is greater than or equal to the source.

var aNumber : Double = 5.2
aNumber.rounded(.up) // 6.0
7

Swift 5

using String method

var yourDouble = 3.12345
//to round this to 2 decimal spaces i could turn it into string
let roundingString = String(format: "%.2f", myDouble)
let roundedDouble = Double(roundingString) //and than back to double
// result is 3.12 

but it's more accepted to use extension

extension Double {
    func round(to decimalPlaces: Int) -> Double {
        let precisionNumber = pow(10,Double(decimalPlaces))
        var n = self // self is a current value of the Double that you will round
        n = n * precisionNumber
        n.round()
        n = n / precisionNumber
        return n
    }
}

and then you can use:

yourDouble.round(to:2)
6

Not Swift but I'm sure you get the idea.

pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
0
5

This seems to work in Swift 5.

Quite surprised there isn't a standard function for this already.

//Truncation of Double to n-decimal places with rounding

extension Double {

    func truncate(to places: Int) -> Double {
    return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
    }

}
5

In iOS 15 / macOS 12 new inline number formatters have been introduced.

Without any rounding rule it rounds like taught in school. The syntax

let value = 1.543240
let rounded = value.formatted(.number.precision(.fractionLength(2))))

rounds down to 1.54 and

let value = 1.545240
let rounded = value.formatted(.number.precision(.fractionLength(2))))

rounds up to 1.55, fractionLength specifies the number of fractional digits

To force rounding down add a rounding rule

let rounded = value.formatted(.number.rounded(rule: .down).precision(.fractionLength(2))))
4

To avoid Float imperfections use Decimal

extension Float {
    func rounded(rule: NSDecimalNumber.RoundingMode, scale: Int) -> Float {
        var result: Decimal = 0
        var decimalSelf = NSNumber(value: self).decimalValue
        NSDecimalRound(&result, &decimalSelf, scale, rule)
        return (result as NSNumber).floatValue
    }
}

ex.
1075.58 rounds to 1075.57 when using Float with scale: 2 and .down
1075.58 rounds to 1075.58 when using Decimal with scale: 2 and .down

4
var n = 123.111222333
n = Double(Int(n * 10.0)) / 10.0

Result: n = 123.1

Change 10.0 (1 decimal place) to any of 100.0 (2 decimal place), 1000.0 (3 decimal place) and so on, for the number of digits you want after decimal..

4

The solution worked for me. XCode 13.3.1 & Swift 5

extension Double {
    
    func rounded(decimalPoint: Int) -> Double {
        let power = pow(10, Double(decimalPoint))
       return (self * power).rounded() / power
    }
}

Test:

print(-87.7183123123.rounded(decimalPoint: 3))
print(-87.7188123123.rounded(decimalPoint: 3))
print(-87.7128123123.rounded(decimalPoint: 3))

Result:

-87.718
-87.719
-87.713
2

I found this wondering if it is possible to correct a user's input. That is if they enter three decimals instead of two for a dollar amount. Say 1.111 instead of 1.11 can you fix it by rounding? The answer for many reasons is no! With money anything over i.e. 0.001 would eventually cause problems in a real checkbook.

Here is a function to check the users input for too many values after the period. But which will allow 1., 1.1 and 1.11.

It is assumed that the value has already been checked for successful conversion from a String to a Double.

//func need to be where transactionAmount.text is in scope

func checkDoublesForOnlyTwoDecimalsOrLess()->Bool{


    var theTransactionCharacterMinusThree: Character = "A"
    var theTransactionCharacterMinusTwo: Character = "A"
    var theTransactionCharacterMinusOne: Character = "A"

    var result = false

    var periodCharacter:Character = "."


    var myCopyString = transactionAmount.text!

    if myCopyString.containsString(".") {

         if( myCopyString.characters.count >= 3){
                        theTransactionCharacterMinusThree = myCopyString[myCopyString.endIndex.advancedBy(-3)]
         }

        if( myCopyString.characters.count >= 2){
            theTransactionCharacterMinusTwo = myCopyString[myCopyString.endIndex.advancedBy(-2)]
        }

        if( myCopyString.characters.count > 1){
            theTransactionCharacterMinusOne = myCopyString[myCopyString.endIndex.advancedBy(-1)]
        }


          if  theTransactionCharacterMinusThree  == periodCharacter {

                            result = true
          }


        if theTransactionCharacterMinusTwo == periodCharacter {

            result = true
        }



        if theTransactionCharacterMinusOne == periodCharacter {

            result = true
        }

    }else {

        //if there is no period and it is a valid double it is good          
        result = true

    }

    return result


}
2

You can add this extension :

extension Double {
    var clean: String {
        return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(format: "%.2f", self)
    }
}

and call it like this :

let ex: Double = 10.123546789
print(ex.clean) // 10.12
1
  • This one is neat implementation of representing it as a String. I wonder if it is possible or rational to write an extension of number of digits representation after period still maintaining it as Double.
    – thinkswift
    Jul 16, 2019 at 18:24
2

Here's one for SwiftUI if you need a Text element with the number value.

struct RoundedDigitText : View {
    let digits : Int
    let number : Double

    var body : some View {
        Text(String(format: "%.\(digits)f", number))
    }
}

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