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.
Related
wanna know how to show this result like int number
var symbol = data[index]["symbol"];
double cureentprice = datarates["price"]["$symbol"];////this double is 1.17150
double enrty = double.parse(data[index]["entryprice"]);////this is 1.17100
double lo = cureentprice - enrty ;//i got like this result 0.00050
as you see above i got the result 0.00050 but i need it like this 50
any idea to do somthing like that??
Try This. Maybe This should Help. If this doesn't work then let me know.
var symbol = data[index]["symbol"];
double cureentprice = datarates["price"]["$symbol"];////this double is 1.17150
double enrty = double.parse(data[index]["entryprice"]);////this is 1.17100
// double lo = cureentprice - enrty ;//i got like this result 0.00050
int scale = 100000;
double lo = currentPrice - enrty;
var value1 = (lo * scale).floor();
var value2 = (lo * scale).ceil();
print(value1);
print(value2);
You can first scale and then round-off using floor() or ceil() function to get desired output.
double currentPrice = 1.17150;
double enrty = 1.17100;
int scale = 100000;
double lo = currentPrice - enrty;
print((lo * scale).floor()); //prints 49
print((lo * scale).ceil()); //prints 50
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))
Is there any proper implementation for 0°00'00.00" format?
NSNumberFormatter supports only groupingSeparator and decimalSeparator.
Or not?
There is no degree-minute-second formatter in Foundation but it's not too hard to roll your own. Here's my crude attempt:
class DegreeFormatter : NumberFormatter {
func string(from degree: Double) -> String {
var remaining = degree
let degree = remaining.rounded(.towardZero)
remaining -= degree
remaining *= 60.0
let minute = remaining.rounded(.towardZero)
remaining -= minute
remaining *= 60
let seconds = remaining
return "\(Int(degree))°\(Int(minute))'\(self.string(from: seconds as NSNumber)!)"
}
}
let formatter = DegreeFormatter()
formatter.maximumFractionDigits = 2
print(formatter.string(from: 1.23456789)) // 1°14'4.44
You can customize it further to include custom degree symbols, whether to include the second, what units are allowed, etc.
What's the best way to create a single Float value from two Ints? I have two vars:
let int1 = 165
let int2 = 5
I'm trying to combine them into a Float with the value 165.5.
Float to Int
Two approaches.
You can concatenate them into a String and pass that to a Float initializer:
let float1 = Float("\(int1).\(int2)")
Or you can divide int2 by 10 and add int1:
let float2 = Float(int1) + Float(int2)/10
Int to Float
If you want to go back, you can again use strings:
let float : Float = 165.5
let intArray = String(float)
.characters
.split(".")
.map { Int(String($0))! }
intArray[0] // 165
intArray[1] // 5
But it's simpler to use math:
let (int1, int2) = (Int(float), (float - floor(float)) * 10)
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)")