here is my code I have 3 UITextfields c, d and e and a button to calculate and display the result into a UITextfield called result but I can't get the result to display 2 decimal places.
func getRootValue() {
if let cText = cValue.text, let dText = dValue.text {
if let doubleC = Double(cText), let doubleD = Double(dText) {
let theSquare = sqrt((doubleC * doubleC) + (doubleD * doubleD))
rootValue.text = "\(theSquare)"
eValue.text = String(Double(eValue.text!)!)
myResult = String(Double(rootValue.text!)! * Double(eValue.text!)! * 2)
roofArea.text = String(Double(rootValue.text!)! * Double(eValue.text!)! * 2)
roofArea.text = (NSString(format:"%.2f")) as String
}
}
}
The result is 0.00 so ive finally got 2 decimal places but its not displaying the actual calculation can anyone give me some help
Related
heightInM = ((Double(heightInFeetText.text!)! * 30.48) + (Double(heightInInchText.text!)! * 2.54))/100
output = Double(weightInKgText.text!)! / (heightInM * heightInM)
bmiOutput.text = String(output)
How can I format double value with 2 decimal points?
Just use stringWithFormat API, add specify how many digits would you like to see.
Example:
let floatValue = 2.333123211
let output = String(format: "%0.2f", floatValue) // prints 2.33
In your case:
bmiOutput.text = String(format: "%0.2f", output)
I'm trying to make a math app with different equations and formulas but I'm trying to circle sector but i just wanted to try to divide the input value by 360 but when I do that it only says 0 unless the value is over 360. I have tried using String, Double and Float with no luck I don't know what I'm doing is wrong but down here is the code. I'm thankful for help but I have been sitting a while and searched online for an answer with no result I might have been searching with the wrong search.
if graderna.text == ""{
}
else{
var myInt: Int? = Int(graderna.text!) // conversion of string to Int
var myInt2: Int? = Int(radien.text!)
let pi = 3.1415926
let lutning = 360
let result = (Double(myInt! / lutning) * Double(pi))
svar2.text = "\(result)"
}
Your code is performing integer division, taking the integer result and converting it to a double. Instead, you want to convert these individual integers to doubles and then do the division. So, instead of
let result = (Double(myInt! / lutning) * Double(pi))
You should
let result = Double(myInt!) / Double(lutning) * Double(pi)
Note, Double already has a .pi constant, so you can remove your pi constant, and simplify the above to:
let result = Double(myInt!) / Double(lutning) * .pi
Personally, I’d define myInt and lutning to be Double from the get go (and, while we’re at it, remove all of the forced unwrapping (with the !) of the optionals):
guard
let text = graderna.text,
let text2 = radien.text,
let value = Double(text),
let value2 = Double(text2)
else {
return
}
let lutning: Double = 360
let result = value / lutning * .pi
Or, you can use flatMap to safely unwrap those optional strings:
guard
let value = graderna.text.flatMap({ Double($0) }),
let value2 = radien.text.flatMap({ Double($0) })
else {
return
}
let lutning: Double = 360
let result = value / lutning * .pi
(By the way, if you’re converting between radians and degrees, it should be 2π/360, not π/360.)
You are dividing an Int by an Int.
Integer division rounds to the nearest integer towards zero. Therefore for example 359 / 360 is not a number close to 1, it is 0. 360 / 360 up to 719 / 360 equals 1. 720 / 360 to 1079 / 360 equals 2, and so on.
But your use of optionals is atrocious. I'd write
let myInt = Int(graderna.text!)
let myInt2 = Int(radien.text!)
if let realInt = myInt, realInt2 = myInt2 {
let pi = 3.1415926
let lutning = 360.0
let result = Double (realInt) * (pi / lutning)
svar2.text = "\(result)"
}
In the line let result = (Double(myInt! / lutning) * Double(pi)) you cast your type to double after dividing two integers so your result will always be zero. You have to make them doubles before division.
let result = (Double(myInt!) / Double(lutning)) * Double(pi))
If you want the value should be correct, then try as
let division = ((Float(V1) / Float(V2)) * Float(pi))
I am storing numbers in a MySQL DB as doubles so I can get min, max and sums.
I have a decimal number 1.66777777778 which equals 01:40:04 however I am wanting to be able to convert this decimal in to hour:minutes:seconds in Swift so I can display the value as 01:40:04 however I don't know how.
I have done some searching but most results are calculators without explanation.
I have this function to convert to decimal:
func timeToHour(hour: String, minute:String, second:String) -> Double
{
var hourSource = 0.00
if hour == ""
{
hourSource = 0.00
}
else
{
hourSource = Double(hour)!
}
let minuteSource = Double(minute)!
let secondSource = Double(second)!
let timeDecimal: Double = hourSource + (minuteSource / 60) + (secondSource / 3600)
return timeDecimal
}
but need one to go back the other way.
Thanks
Try:
func hourToString(hour:Double) -> String {
let hours = Int(floor(hour))
let mins = Int(floor(hour * 60) % 60)
let secs = Int(floor(hour * 3600) % 60)
return String(format:"%d:%02d:%02d", hours, mins, secs)
}
Basically break each component out and concatenate them all together.
Im trying to cast the results of a calculation (ShotPercentage) to a Float and present the results in the App as a 89 percent for example. But I am struggling with the type casting any help would be greatly appreciated. Here is my code:
// calculate shot percentage
shotPercentage = makeCounter / totalCounter
shotPercentageLabel.text = "\(shotPercentage)"
You can apply a conversion to your Floatresult like this.
shotPercentage = Int(makeCounter / totalCounter)
var shotPercentageInt: Int
shotPercentageInt = 3/5
println("\(shotPercentageInt*100)%") // 0% because 3/5 = 0.6 -> Int = 0
//
var shotPercentageFloat: Float
shotPercentageFloat = 3/5
println("\(shotPercentageFloat*100)%") // 60.0% because 3/5 = 0.6 -> Float = 60%
// Convert Float to Int
var shotPercentageFloatToInt: Int
shotPercentageFloatToInt = Int(shotPercentageFloat)
println("\(shotPercentageFloat)") // 0.6
// It's amazing
You might want to use NSNumberFormatter. It does well going to strings and coming from strings. Regardless, it would look like:
let makeCounter = 15
let totalCounter = 20
let shotPercentage:Float = makeCounter / totalCounter
let formatter = NSNumberFormatter()
formatter.numberStyle = .PercentStyle
if let percentString = formatter.stringFromNumber(shotPercentage) {
shotPercentageLabel.text = percentString
}
In this case the label would read 75%, as the formatter will include the percent sign for you.
When logging-out a float in Objective-C you can do the following to limit your output to only 2 decimal places:
float avgTemp = 66.844322156
NSLog (#"average temp. = %.2f", avgTemp);
But how do you do this in Swift?
And how do you escape other characters in println in Swift?
Here's a regular Swift println statement:
println ("Avg. temp = \(avgTemp)")
So how do you limit decimal places?
Also, how do you escape double-quotes in println?
Here's the shortest solution I found thus far:
let avgTemp = 66.844322156
println(NSString(format:"%.2f", avgTemp))
Its like the swift version of NSString's stringWithFormat
Everything about the format of a number as a string can be adjusted using a NSNumberFormatter:
let nf = NSNumberFormatter()
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
nf.maximumFractionDigits = 2
println(nf.stringFromNumber(0.33333)) // prints 0.33
You can escape quotes with a backslash
println("\"God is dead\" -Nietzsche")
Println() is deprecated.
var avgTemp = 66.844322156
print("average temp. = (round(avgTemp*100)/100)") // average temp. = 66.84
//or
print(NSString(format:"average temp. = %.2f", avgTemp))) // average temp. = 66.84
avgTemp = 66.846322156
print(String(format:"average temp. = %.2f", avgTemp)) // average temp. = 66.85
If you need to print floating point numbers often with a certain precision, you could extend Float and Double with convenience methods. For example, for 2 significant figure precision:
// get Float or Double with 2 significant figure precision
var numberFormatter = NSNumberFormatter()
extension Float {
var sf2:String {
get {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
numberFormatter.maximumSignificantDigits = 2
return numberFormatter.stringFromNumber(self)!
}
}
}
extension Double {
var sf2:String {
get {
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
numberFormatter.maximumSignificantDigits = 2
return numberFormatter.stringFromNumber(self)!
}
}
}
Then when you need to print things:
let x = 5.23325
print("The value of x is \(x.sf2)")