Getting the Decimal Part of a Double in Swift

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

Get value after decimal point from double variable

Divide the double by 1 using truncatingRemainder(dividingBy:) and get the reminder.

var doubleVar = 234.045
var new = doubleVar.truncatingRemainder(dividingBy: 1.0)
let rounded = Double(round(1000*new)/1000)
print(rounded)

OR

Using C function modf

var doubleVar = 234.045
let splitPi = modf(doubleVar)
splitPi.0 // 324.0
splitPi.1 // 0.045

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

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
}
}

Is there any way to iterate the decimal part of a double var in swift 4?

If the intention is to get many decimal digits of 1.0/98.0 then you must not store that number in a Double in the first place, because that has a precision of approximately 16 decimal digits only. You could use Decimal which has a precision of 38 decimal digits.

But for more decimal digits you'll have to do “rational arithmetic,” i.e. work with numerator and denominator of the fraction as integers.

Here is how you can print arbitrarily many decimal digits of a rational number. For simplicity I have assumed that the number is positive and less than one.

func printDecimalDigits(of numerator: Int, dividedBy denominator: Int, count: Int) {
var numerator = numerator
for _ in 1...count {
// Multiply by 10 to get the next digit:
numerator *= 10
// Print integer part of `numerator/denominator`:
print(numerator / denominator, terminator: "")
// Reduce `numerator/denominator` to its fractional part:
numerator %= denominator
}
print()
}

Example:

printDecimalDigits(of: 1, dividedBy: 98, count: 100)
// 0102040816326530612244897959183673469387755102040816326530612244897959183673469387755102040816326530

Or as a function which returns the digits as a (lazily evaluated) sequence:

func decimalDigits(of numerator: Int, dividedBy denominator: Int) -> AnySequence<Int> {
return AnySequence(sequence(state: numerator) { num -> Int in
num *= 10
let d = num / denominator
num %= denominator
return d
})
}

Example:

let first1000Digits = decimalDigits(of: 1, dividedBy: 98).prefix(1000)
for d in first1000Digits { print(d) }

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"

Removing the decimal part of a double without converting it to Int in swift

I recommend NumberFormatter, this example creates a reusable formatter.

let decimalFormatter : NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter
}()

private var displayValue : Double {
get {
return Double(display.text!)!
}
set {
display.text = decimalFormatter.string(for: newValue)
}
}

How to get a Double value up to 2 Decimal places

You can simply do this:

let pi = 3.14159

let text = String(format: "%.2f", arguments: [pi])

print(text) // output = 3.14


Related Topics



Leave a reply



Submit