How to Truncate Decimals to X Places in Swift

How to truncate decimals to x places in Swift

You can tidy this up even more by making it an extension of Double:

extension Double {
func truncate(places : Int)-> Double {
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}

You use it like this:

var num = 1.23456789
// return the number truncated to 2 places
print(num.truncate(places: 2))

// return the number truncated to 6 places
print(num.truncate(places: 6))

Rounding a double value to x number of decimal places in swift

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.

EDIT:

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

Easily truncating a Double - swift

You can use NumberFormatter:

extension Formatter {
static let number = NumberFormatter()
}

extension FloatingPoint {
func fractionDigitsRounded(to digits: Int, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
Formatter.number.roundingMode = roundingMode
Formatter.number.minimumFractionDigits = digits
Formatter.number.maximumFractionDigits = digits
return Formatter.number.string(for: self) ?? ""
}
}

let value = 19.3563443
let roundedToFive = value.fractionDigitsRounded(to: 5) // "19.35634"

Round up double to 2 decimal places

Use a format string to round up to two decimal places and convert the double to a String:

let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!
railRatioLabelField.text! = String(format: "%.2f", currentRatio)

Example:

let myDouble = 3.141
let doubleStr = String(format: "%.2f", myDouble) // "3.14"

If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):

let myDouble = 3.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"

Rounding a double to 2 decimal places in Swift, XCode 12

You could do it directly inside Text with the help of string interpolation:

struct ContentView: View {
let decimalNumber = 12.939010

var body: some View {
Text("\(decimalNumber, specifier: "%.2f")")//displays 12.94
}
}

Easiest way to truncate float to 2 decimal places?

You cannot round a Float or Double to 2 decimal digits exactly.
The reason is that these data types use a binary floating point representation,
and cannot represent numbers like 0.1 or 0.01 exactly.
See for example

  • Why Are Floating Point Numbers Inaccurate?
  • What Every Computer Scientist Should Know About Floating-Point Arithmetic

But you said:

I need my return value to be in quarter steps (i.e. 6.50, 6.75, 5.25, etc),

and that is exactly possible because 0.25 = 2-2 can be represented exactly as a floating point number.

The round() function rounds a floating point number to the nearest integral value.
To round to the nearest quarter, you just have to "scale" the calculation with the factor 4:

func roundToNearestQuarter(num : Float) -> Float {
return round(num * 4.0)/4.0
}

roundToNearestQuarter(6.71) // 6.75
roundToNearestQuarter(6.6) // 6.5

How to truncate/round NSNumber to one decimal place

Just a few more options:

  1. Do you need it to be rounded exactly to one decimal place? If so, you can use Decimal.

     var number = NSNumber(1.45654)

    var decimalValue = number.decimalValue
    var result: Decimal = 0
    NSDecimalRound(&result, &decimalValue, 1, .plain)
    print(result)
  2. However if you just want to display it to one decimal place, you might use NumberFormatter.

     let number = NSNumber(1.45654)

    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.minimumFractionDigits = 1
    formatter.maximumFractionDigits = 1
    guard let result = formatter.string(for: number) else { return }
    print(result)

Round a double down to one decimal place (dropping decimal places)

Use the function trunc() (which stands for truncate) which will chop away the decimal portion without rounding. Specifically, multiply the Double value by 10, truncate it, then divide by 10 again. Then, to display using 1 decimal place, use String(format:):

let aDouble = 1.15
let truncated = trunc(aDouble * 10) / 10
let string = String(format: "%.1f", truncated
print(string)

(displays "1.1")

or, to process an entire array of sample values:

let floats = stride(from: 1.099, to: 2.0, by: 0.1)

let truncs = floats
.map { trunc($0 * 10) / 10 }
.map { String(format: "%.1f", $0) }

let beforeAndAfter = zip(floats, truncs)
.map { (float: $0.0, truncString: $0.1)}

beforeAndAfter.forEach { print(String(format: "%.3f truncated to 1 place is %@", $0.0, $0.1)) }

Outputs:

1.099 truncated to 1 place is 1.0
1.199 truncated to 1 place is 1.1
1.299 truncated to 1 place is 1.2
1.399 truncated to 1 place is 1.3
1.499 truncated to 1 place is 1.4
1.599 truncated to 1 place is 1.5
1.699 truncated to 1 place is 1.6
1.799 truncated to 1 place is 1.7
1.899 truncated to 1 place is 1.8
1.999 truncated to 1 place is 1.9

Getting the decimal part of a double in Swift

Without converting it to a string, you can round up to a number of decimal places like this:

let x:Double = 1234.5678
let numberOfPlaces:Double = 4.0
let powerOfTen:Double = pow(10.0, numberOfPlaces)
let targetedDecimalPlaces:Double = round((x % 1.0) * powerOfTen) / powerOfTen

Your output would be

0.5678



Related Topics



Leave a reply



Submit