iOS Swift: Create Float value from two Ints - swift

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)

Related

How to obtain precision of two numbers after the decimal point but without rounding the double in SWIFT [duplicate]

This question already has answers here:
How to truncate decimals to x places in Swift
(10 answers)
Closed 3 years ago.
I am new with swift and I need help. I want to get first two digits after the decimal point, for example -
1456.456214 -> 1456.45
35629.940812 -> 35629.94
without rounding the double to next one.
Try the below code
let num1 : Double = 1456.456214
let num2 : Double = 35629.940812
let numberFormatter = NumberFormatter()
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.roundingMode = .down
let str = numberFormatter.string(from: NSNumber(value: num1))
let str2 = numberFormatter.string(from: NSNumber(value: num2))
print(str)
print(str2)
Output
1456.45
35629.94
To keep it a double you can do
let result = Double(Int(value * 100)) / 100.0
or, as #vacawama pointed out, use floor instead
let result = floor(value * 100) / 100
extension Double {
func truncate(places : Int)-> Double
{
return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
}
}
and use this like as;
let ex: Double = 35629.940812
print(ex.truncate(places: 2)) //35629.94
let ex1: Double = 1456.456214
print(ex1.truncate(places: 2)) //1456.45

Odd division result in swift [duplicate]

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

Cast an int to a Float in Swift

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.

Swift: "float is not convertible to int"

How can I convert this to Int? I've tried using the initializer: Int(), using the round method.. All of them generates an error. In this case the one I get is: "float is not convertible to int"
let CirclePoints = 84
let PI = 3.14159
let radius: Double!
let xBase: Int!
let yBase: Int!
var xPos = Int()
var yPos = Int()
xPos = round(xBase + radius * cos((PI / 10) * circlePoint))
I'd recommend converting all of your values to double since that is what the round function takes. The round function also returns a double, so you'll have to convert the result of round() into an Int to store it in xPos.
xPos = Int(round(Double(xBase) + Double(radius) * cos((PI / 10) * Double(circlePoint))))
Note that the conversion process here is actually creating new double values from the variables, not changing those variables.

Generating random values in Swift between two integer values

I'm trying to generate random values between two integers. I've tried this, which starts from 0,
let randomNumber = arc4random_uniform(10)
println(randomNumber)
But I need a value between 10 and 50.
try this
let randomNumber = arc4random_uniform(40) + 10
println(randomNumber)
in general form
let lower : UInt32 = 10
let upper : UInt32 = 50
let randomNumber = arc4random_uniform(upper - lower) + lower
println(randomNumber)
This is an option for Swift 4.2 and above using the random() method, which makes it easy!
let randomInt = Int.random(in: 10...50)
The range can be a closed (a...b) or half open (a..<b) range.
If you want a reusable function with simple parameters:
func generateRandomNumber(min: Int, max: Int) -> Int {
let randomNum = Int(arc4random_uniform(UInt32(max) - UInt32(min)) + UInt32(min))
return randomNum
}
more simple way of random number generator
func random(min: Int, max: Int) -> Int {
return Int(arc4random_uniform(UInt32(max - min + 1))) + min
}