What is the swift code to apply Round Up or Down Sum Amount? - swift

I try on Xcode - Playground.
This is my code. Beginner.
========
import UIKit
var num1 : Double = 0.055 // Stock Price
var num2 : Double = 18 // Lots
var num3 : Double = 1000 // Share Per Lots
var sum1 : Double = num1 * num2 * num3 // Gross Share Price
var sum5 : Double = sum1 * (0.03/100) // Clearing Charges // Answer Playground Return is " 0.297 "
My Questions is the "sum5" I want answer round up and display " 0.30 "
It is possible in swift code ?
Thanks.

You can get it this way:
var roundOfSum5 : Double = Double(round(100 * sum5)/100) //0.3

Regarding to that answer
If you need to round to a specific place, then you multply by pow(10.0, numberOfPlaces), round, and then divide by pow(10, numberOfPlaces). In your case the number of places is 2.0:
let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let rounded = round(sum5 * multiplier) / multiplier
print(rounded) // 0.3
If you have a number like sum5 = 0.3465 and you want to round to the third place after the decimal you can use 3.0 for numberOfPlaces and get as result 0.347

Related

Get double hours from double minute in Swift 2

I'm using Swift 2. I have double myMinute and I want to convert it to double hours(myHours). How can I do it? My codes under below
let myMinute : Double = 62.0
let myHours : Double = ?
I want to show with math example: myhours = 1.0
Found this here!
func minutesToHoursMinutes (minutes : Int) -> (hours : Int , leftMinutes : Int {
return (minutes / 60, (minutes % 60))
}
let timeTuple = minutesToHoursMinutes(minutes: 100)
timeTuple.hours /// 1
timeTuple.leftMinutes /// 40
The value should be 1.03 not 1.02 if you use the current value of minute (you can check with calculator) and it is a simple math, i think what you want beside the calculation is how to round the value to 2 decimal point. You should've made it clearer. This will do the work.
myHours = Double(round(myMinute / 60 * 100) / 100)
print(myHours)

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

Swift 3 - To the power of (pow) function not working as expected

Please could somebody help me. I am trying to run a simple compounding calculation in Swift.
Formula I am trying to recreate:
T = P(1+r/n)^(n*t), where
T = Total, P = Starting amount, r = interest rate, n = number of times compounded and t = number of years
My code as follows:
import Darwin
var total: Double
var startingAmount: Double = 5000.00
var interestRate: Double = 0.05
var numberOfTimesCompounded: Double = 4.0
var numberOfYears: Double = 2.0
var totalYear1: Double
var toThePowerOf: Double
totalYear1 = startingAmount * (1 + interestRate / numberOfTimesCompounded)
toThePowerOf = numberOfTimesCompounded * number of years
total = pow(totalYear1,toThePowerOf)
The answer to the formula should be 5,522.43
In my code above, TotalYear1 = 5062.50 (which is correct) and toThePowerOf = 8.0 (which is correct) However, total shows = 4314398832739892000000.00 which clearly isn't right. Could anyone tell me what I am doing wrong with my calculation of total?
Many thanks
You've actually implemented T = (P(1+r/n))^(n*t), which doesn't even make dimensional sense.
startingAmount needs to be multiplied at the end, it can't be part of the pow:
totalYear1 = (1 + interestRate / numberOfTimesCompounded)
toThePowerOf = numberOfTimesCompounded * number of years // [sic]
total = startingAmount * pow(totalYear1,toThePowerOf)

Why can't I divide integers correctly within reduce in Swift?

I'm trying to get the average of an array of Ints using the following code:
let numbers = [1,2,3,4,5]
let avg = numbers.reduce(0) { return $0 + $1 / numbers.count }
print(avg) // 1
Which is obviously incorrect. However, if I remove the division to the outside of the closure:
let numbers = [1,2,3,4,5]
let avg = numbers.reduce(0) { return $0 + $1 } / numbers.count
print(avg) // 3
Bingo! I think I remember reading somewhere (can't recall if it was in relation to Swift, JavaScript or programming math in general) that this has something to do with the fact that dividing the sum by the length yields a float / double e.g. (1 + 2) / 5 = 0.6 which will be rounded down within the sum to 0. However I would expect ((1 + 2) + 3) / 5 = 1.2 to return 1, however it too seems to return 0.
With doubles, the calculation works as expected whichever way it's calculated, as long as I box the count integer to a double:
let numbers = [1.0,2.0,3.0,4.0,5.0]
let avg = numbers.reduce(0) { return $0 + $1 / Double(numbers.count) }
print(avg) // 3
I think I understand the why (maybe not?). But I can't come up with a solid example to prove it.
Any help and / or explanation is very much appreciated. Thanks.
The division does not yield a double; you're doing integer division.
You're not getting ((1 + 2) + 3 etc.) / 5.
In the first case, you're getting (((((0 + (1/5 = 0)) + (2/5 = 0)) + (3/5 = 0)) + (4/5 = 0)) + (5/5 = 1)) = 0 + 0 + 0 + 0 + 0 + 1 = 1.
In the second case, you're getting ((((((0 + 1) + 2) + 3) + 4) + 5) / 5) = 15 / 5 = 3.
In the third case, double precision loss is much smaller than the integer, and you get something like (((((0 + (1/5.0 = 0.2)) + (2/5.0 = 0.4)) + (3/5.0 = 0.6)) + (4/5.0 = 0.8)) + (5/5.0 = 1.0)).
The problem is that what you are attempting with the first piece of code does not make sense mathematically.
The average of a sequence is the sum of the entire sequence divided by the number of elements.
reduce calls the lambda function for every member of the collection it is being called on. Thus you are summing and dividing all the way through.
For people finding it hard to understand the original answer.
Consider.
let x = 4
let y = 3
let answer = x/y
You expect the answer to be a Double, but no, it is an Int. For you to get an answer which is not a rounded down Int. You must explicitly state the values to be Double. See below
let doubleAnswer = Double(x)/Double(y)
Hope this helped.

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.