How to Change the Number of Decimal Places iOS

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

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"

Round a digit upto two decimal place in Swift

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 = Double(String(format: "%.2f", myDouble)) // 3.14

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 :

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

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

How do I change the number of decimal places iOS?

One way is to use NSNumberFormatter to format your result instead of NSString's -stringWithFormat::

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:requiredDigits];
[formatter setMinimumFractionDigits:0];
NSString *result = [formatter stringFromNumber:[NSNumber numberWithFloat:currentNumber];

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

change the fontsize of the decimal number in Swift/ SwiftUI

When you know exact format of your string, like in this case minimum string length will be 4("0.00") , you can safely use dropLast and dropFirst.

I suggest moving 2 to priceFractionDigits constant to reduce constants usage in your code.

Then you can use string concatenation, it'll align Text by baseline.

struct BalanceText: View {
var balance: Float
var balanceString: String {
return balance.formattedWithSeparator
}

var body: some View {
Text(balanceString.dropLast(priceFractionDigits))
.font(.system(size: 24))
+
Text(balanceString.dropFirst(balanceString.count - priceFractionDigits))
.font(.system(size: 18))
}
}

private let priceFractionDigits = 2

extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal

// minimum decimal digit, eg: to display 2 as 2.00
formatter.minimumFractionDigits = priceFractionDigits

// maximum decimal digit, eg: to display 2.5021 as 2.50
formatter.maximumFractionDigits = priceFractionDigits

return formatter
}()
}

Usage

BalanceText(balance: balance)

Sample Image

How to limit the textfield entry to 2 decimal places in swift 4?

Set your controller as the delegate for the text field and check if the proposed string satisfy your requirements:

override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
textField.keyboardType = .decimalPad
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let r = Range(range, in: oldText) else {
return true
}

let newText = oldText.replacingCharacters(in: r, with: string)
let isNumeric = newText.isEmpty || (Double(newText) != nil)
let numberOfDots = newText.components(separatedBy: ".").count - 1

let numberOfDecimalDigits: Int
if let dotIndex = newText.index(of: ".") {
numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
} else {
numberOfDecimalDigits = 0
}

return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
}


Related Topics



Leave a reply



Submit