Reputation: 55
I have a few calculations that perform after I select the "Calculate" function. The results vary depending on the values entered. I need to limit the results to 2 decimal places. I have tried numerous options with no luck. Any help here would be appreciated. Again, I am using Swift 4 in an iOS app.
Here is a bit of the code I am using:
@IBOutlet weak var f0TextField: UITextField!
@IBAction func calculateButton(_ sender: Any) {
f0TextField.text = "\(((Double(f1TextField.text ?? "%.2f") ?? 0.0) + (Double(f2TextField.text ?? "%.2f") ?? 0.0))/2)"
I have 6 more "textfields" that I have to apply this to also.
Upvotes: 0
Views: 1322
Reputation: 4855
Try using common Extension for Double
extension Double
{
//MARK: Rounds the double to decimal places value
/**
This func return Double to rounded Place
- paramter places : Number of places to be rounded
*/
func rounded(toPlaces places:Int) -> Double
{
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
Usgae - Double(newValue).rounded(toPlaces: 0)
Upvotes: 0
Reputation: 318774
You need to break up that code. First get the text of the two text fields. Then convert the two text values to Double
. Then add the two numbers. Then convert the sum to a string formatted as desired.
Here's one way:
if let val1 = Double(f1TextField.text ?? "0"), let val2 = Double(f12TextField.text ?? "0") {
let sum = val1 + val2
f0TextField.text = String(format: "%.2f", sum)
}
But you really should use NumberFormatter
to show the result in a proper locale sensitive way. And most likely you need it to parse the user entered numbers as well.
You probably should also create a function that takes any two text fields and returns a String
that you can then set on the appropriate text field.
Upvotes: 0
Reputation: 377
Credits to @Sebastian, used his suggested code and it works. You can try if it works for you
First have this extension
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
}}
then
let x = Double(textField.text).rounded(toPlaces: 2)
print(x) // to see if it works
Upvotes: 0
Reputation: 1270
If you want final answer in 2 decimal places than you should apply it to final result like below.
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"
Upvotes: 1