IOS: Get two digits of a double (€) NOT to display the value, just return it - ios

I´ve read a lot of posts about this but all of them were to limit the number digits to show them(NSString) .In my case I have:
I compare two double values(wich are the "same"), each of them got from different mathematical operations. For example: (4.800000 and 4.800000)
double result1=4.800000, result2=4.800000
//compare the results:
if(result1==result2){
msg.text=#"well done!!";
}else if(result1>result2){
msg.text=#"continue your work";
}
"I´m working with money (4,80€)"
In the msg label i get "continue your work" message, not the "well done". I don´t even know if the comparison is done in a correct way.
I think that the best idea would be to limit 4.800000 to 4.80 in order to delete small values and get a exact comparison.(how could i do this?)
I DONT WANT to limit the number to two digits just to PRINT the solution, I want to WORK with that number.

You can do something like this:
double a = 2.55000, b = 2.55002;
if(fabs(a-b)<1e-3) {
// code here, a == b
} else {
// code here, a != b
}

use floor(<#double#>) to round down OR just subtract them and floor the result.

For a nice answer to this problem see:
https://stackoverflow.com/a/10335601/474896
Which could be summarized as a simple as:
if (fabs(x-y) < FLT_EPSILON) {/* ... */}
However since you you're working with money values you should check out NSDecimalNumber.
Or as Marcus Zarra puts it:
"If you are dealing with currency at all, then you should be using
NSDecimalNumber.".

Related

what's the use of .count command in repeat while loop?

I recently began to study swift as my first programming language and there's a very simple term that i can't find an answer for it.
take a look at this code:
var a = [Int]()
repeat {
let randomNumbers = Int.random(in: 0...10)
if a.contains(randomNumbers) == false {
a.append(randomNumbers)
}
print(randomNumbers)
} while (a.count < 10)
so this code is supposed to add 10 numbers (no duplicates) from 0...10 into the array until all unique integers are listed. what I don't understand is the role of "while" here.
doesn't the last line mean the number of "generated numbers" must be less than 10? then why every time I run the code I get more than 10 numbers (say 30-40) in the console?
Also according to the code, this code must not generate dupes. then why do I get some numbers printed 2,3 times in the console?
you check if randomNumbers already added to array a, if yes, the loop will be executed again, until a.count < 10.
if you move the print statement inside the if statement, it will be printed exactly 10 times.

Google sheets recursive ROUND for fractional parts

I have a number with fractional parts, but Google sheets ROUND function works only for first number specified in places parameter:
1.48852 => ROUND(1.48852) => 1
1.48852 => ROUND(ROUND(ROUND(ROUND(ROUND(ROUND(1.48852,5),4),3),2),1),0) => 2
Is any function in Google sheets that would work as shown in the second case?
Basically, I want something like ROUND but work recursively.
To answer your question directly, no, I don't believe that there is any function that enables recursive rounding (or recursive anything for that matter).
However, with the same degree of curiosity that you showed in asking this question, I've looked at how I might achieve a recursive result through scripting. This is the result.
function reround(input) {
var num1 = 5;
do {
input = input.toFixed(num1);
input=+input;
num1--;
}while (num1 >-1); // continue running the loop while is greater than -1, i.e. until num1 = 0
return input;
}
This code gets entered as a script and then the function is available for use in the spreadsheet. It only takes one parameter (value) because the number of places is coded into the script. But no doubt, one could modify the code to accept the number of decimal places as a parameter also (I wasn't that curious;).
This is the sequence of values at each stage of the conventional and recursive rounding.
This is the log of values from the REROUND process.
Interesting to note the difference at three decimal places. It's not something that I've explored, so I don't have an explanation.

Swift - compare words and filtering

i just started learning Swift and trying to make an assignment for iOS.
what i have is 4 categories of keywords, for example:
CategoryX: hello, bye, good, bad
CategoryY: rain, sun
CategoryZ: sun, hello, what, rain
CategoryV: yes, no, bad, music, song, note
what i want is to compare this categories with each other and the result will give me the keywords that are in the choosen categories.
for example if i choose to compare all the categories, the results will be: null
(because there is no keyword that appear in all categories)
but if i choose X and Z, then the result will be: hello
if Y and Z then its: sun, rain
I’m not asking from anyone to write me the code (but ofc would be nice if someone gave me a headstart), i just want little explanation of how to deal with this problem and what to use to do it the right way, can someone shed some light?
thank you
I’m not asking from anyone to write me the code (but ofc would be nice if someone gave me a headstart), i just want little explanation of how to deal with this problem and what to use to do it the right way, can someone shed some light?
Okay, without giving the answer away, here’s a hint about how to deal with the problem., to give you a head start.
Doesn't this assignment make you think about sets? Remember those Venn diagrams you had to make in high school? Remember the idea of the intersection of sets? Think about that. Think about sets. Hmmm... Swift has a Set struct...
If you follow up that idea, and research what a Set is in Swift, you’ll see what to do.
Had fun writing it so I post it here. If you aren’t finished by now then look at the result and learn from it(my motto).
I expect you to learn .forEach, .map, .filter, guard let and optional subscript, since you skipped the easy answer with Sets. Oh don’t forget closures and how they strongly capture.
func compare(dicts: [[String]]) -> [String] {
var result = [String: Int]()
dicts.forEach { arg0 in
guard let priorResult = result[arg0.key] else {
result[arg0.key] = arg0.value
return
}
result[arg0.key] = priorResult + arg0.value
}
return result.filter{ arg0 in return arg0.value == dicts.count }.map{ return $0.key }
}
.map, forEach and .filter call for every item in the collection(for every key-value pair in a dictionary) thegiven closure.
.map returns an array of what is returned inside map.
.filter returns an array of items for which the closure returned true and so filtering out the items for which the closure returned false.
.forEach is an alternative to a for-loop.
result counts every occurance of a string.
.filter returns true for the strings which occured inside every dict.
.map maps the dictionary’s keys to a simple [String] array.
You can try
let set1 = Set(["123","456","789"])
let set2 = Set(["123","456"])
let set3 = Set(["123"])
let res12 = set1.intersection(set2) // ["123","456"]
let res123 = set1.intersection(set2).intersection(set3) // ["123"]

Finding the number of digits in a number restricted number of tools since I am a Python beginner

def digits(n):
total=0
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))=>1:
total+=i
else:
total+=0
return total
I want to find the number of digits in 13 so I do the below
print digits(13)
it gives me $\0$ for every number I input into the function.
there's nothing wrong with what I've written as far as I can see:
if a number has say 4 digits say 1234 then dividing by 10^4 will make it less than 1: 0.1234 and dividing by 10^3 will make it 1.234
and by 10^3 will make it 1.234>1. when i satisfies BOTH conditions you know you have the correct number of digits.
what's failing here? Please can you advise me on the specific method I've tried
and not a different one?
Remember for every n there can only be one i which satisfies that condition.
so when you add i to the total there will only be i added so total returning total will give you i
your loop makes no sense at all. It goes from 0 to exact number - not what you want.
It looks like python, so grab a solution that uses string:
def digits(n):
return len(str(int(n))) # make sure that it's integer, than conver to string and return number of characters == number of digits
EDIT:
If you REALLY want to use a loop to count number of digits, you can do this this way:
def digits(n):
i = 0
while (n > 1):
n = n / 10
++i
return i
EDIT2:
since you really want to make your solution work, here is your problem. Provided, that you call your function like digits(5), 5 is of type integer, so your division is integer-based. That means, that 6/100 = 0, not 0.06.
def digits(n):
for i in range(0,n):
if n/float(10**(i))<1 and n/float(10**(i-1))=>1:
return i # we don't need to check anything else, this is the solution
return null # we don't the answer. This should not happen, but still, nice to put it here. Throwing an exception would be even better
I fixed it. Thanks for your input though :)
def digits(n):
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))>=1:
return i

Lua random number to the 8th decimal place

How do I get a random number in Lua to the eighth decimal?
Example : 0.00000001
I have tried the following and several variations of this but can not get the format i need.
math.randomseed( os.time() )
x = math.random(10000000,20000000) * 0.00000001
print(x)
i would like to put in say 200 and get this 0.00000200
Just grab a random number from 0-9, and slide it down 6 places. You can use format specifiers to create the string representation of the number that you desire. For floats we use %f, and indicate how many decimal places we want to have with an intermediate .n, where n is a number.
math.randomseed(os.time())
-- random(9) to exclude 0
print(('%.8f'):format(math.random(0, 9) * 1e-6))
--> '0.00000400'
string.format("%.8f",math.random())
to help anyone else. my question should have been worded a bit better. i wanted to be able to get random numbers and get it to the 8th decimal place.
but i wanted to be able to have those numbers from 1-10,000 so he is updated how i wanted it and the help of Oka got me to this
math.randomseed(os.time())
lowest = 1
highest = 7000
rand=('%.8f'):format(math.random(lowest, highest) / 100000000)
print(rand)
Hope this helps someone else or if it can be cleaned up please let me know

Resources