Always display a certain number of digits - ios

I am creating a calculator app. For aesthetic reasons (numbers need to line up with an image), the result always needs to be five digits long, even if the first four digits are spaces or zeros. For example, the user enters 1+1, the result is 2, but my app should display it as "00002" or " 2".
How can I achieve this?

Well, you contradict yourself when you say the number should always be five digits long then say your app should display it as "00002" or "2". I'll assume you actually want the former? Here's a simple example assuming your number is int x.
int x = 2;
NSString *string = [NSString stringWithFormat:#"%05d", x];

Related

Divide large number by 1000 and round to one decimal place

I am finding it very difficult to do a simple operation, take a large number (4 digits or above) divide by 1000, round to one decimal place and then display as a string with K but perhaps I am missing an obvious answer. (There are tons of questions on this on SO but no one seems to agree on a good answer.)
I would like the following to display as 5.6K.
int startingint = 5654;
int formatted = startingint/1000;
NString *formattedstr = [NSString stringWithFormat:#"%dK", formatted];
Instead, it displays 5K.
Can anyone suggest how to get it to show an extra decimal place?
Thanks in advance for any suggestions.
You can try
float starting = 5654.0;
float formatted = starting/1000.0;
NString *formattedstr = [NSString stringWithFormat:#"%.1fK", formatted];

Calculating ISIN checksum

HI I know there have been may question about this here but I wasn't able to find a detailed enough answer, Wikipedia has two examples of ISIN and how is their checksum calculated.
The part of calculation that I'm struggling with is
Multiply the group containing the rightmost character
The way I understand this statement is:
Iterate through each character from right to left
once you stumble upon a character rather than digit record its position
if the position is an even number double all numeric values in even position
if the position is an odd number double all numeric values in odd position
My understanding has to be wrong because there are at least two problems:
Every ISIN starts with two character country code so position of rightmost character is always the first character
If you omit the first two characters then there is no explanation as to what to do with ISINs that are made up of all numbers (except for first two characters)
Note
isin.org contains even less information on verifying ISINs, they even use the same example as Wikipedia.
I agree with you; the definition on Wikipedia is not the clearest I have seen.
There's a piece of text just before the two examples that explains when one or the other algorithm should be used:
Since the NSIN element can be any alpha numeric sequence (9 characters), an odd number of letters will result in an even number of digits and an even number of letters will result in an odd number of digits. For an odd number of digits, the approach in the first example is used. For an even number of digits, the approach in the second example is used
The NSIN is identical to the ISIN, excluding the first two letters and the last digit; so if the ISIN is US0378331005 the NSIN is 037833100.
So, if you want to verify the checksum digit of US0378331005, you'll have to use the "first algorithm" because there are 9 digits in the NSIN. Conversely, if you want to check AU0000XVGZA3 you're going to use the "second algorithm" because the NSIN contains 4 digits.
As to the "first" and "second" algorithms, they're identical, with the only exception that in the former you'll multiply by 2 the group of odd digits, whereas in the latter you'll multiply by 2 the group of even digits.
Now, the good news is, you can get away without this overcomplicated algorithm.
You can, instead:
Take the ISIN except the last digit (which you'll want to verify)
Convert all letters to numbers, so to obtain a list of digits
Reverse the list of digits
All the digits in an odd position are doubled and their digits summed again if the result is >= 10
All the digits in an even position are taken as they are
Sum all the digits, take the modulo, subtract the result from 0 and take the absolute value
The only tricky step is #4. Let's clarify it with a mini-example.
Suppose the digits in an odd position are 4, 0, 7.
You'll double them and get: 8, 0, 14.
8 is not >= 10, so we take it as it is. Ditto for 0. 14 is >= 10, so we sum its digits again: 1+4=5.
The result of step #4 in this mini-example is, therefore: 8, 0, 5.
A minimal, working implementation in Python could look like this:
import string
isin = 'US4581401001'
def digit_sum(n):
return (n // 10) + (n % 10)
alphabet = {letter: value for (value, letter) in
enumerate(''.join(str(n) for n in range(10)) + string.ascii_uppercase)}
isin_to_digits = ''.join(str(d) for d in (alphabet[v] for v in isin[:-1]))
isin_sum = 0
for (i, c) in enumerate(reversed(isin_to_digits), 1):
if i % 2 == 1:
isin_sum += digit_sum(2*int(c))
else:
isin_sum += int(c)
checksum_digit = abs(- isin_sum % 10)
assert int(isin[-1]) == checksum_digit
Or, more crammed, just for functional fun:
checksum_digit = abs( - sum(digit_sum(2*int(c)) if i % 2 == 1 else int(c)
for (i, c) in enumerate(
reversed(''.join(str(d) for d in (alphabet[v] for v in isin[:-1]))), 1)) % 10)

Why, in Swift, when I convert from a Double to an Int is it subtracting 1?

I have some very simple code that does a calculation and converts the resulting double to an int.
let startingAge = (Double(babyAge/2).rounded().nextDown)
print(startingAge)
for each in 0..<allQuestions.count {
if allQuestions[each] == "\(Int(startingAge))"
The first print of startingAge gives me the correct answer, for example 5.0. But when it converts to an Int, it gives me an answer of 4. When the Double is 6.0, the int is 5.
I'm feeling stupid, but can't figure out what I'm doing wrong.
When you call rounded(), you round your value to the nearest integer.
When you call .nextDown, you get the next possible value less than the existing value, which means you now have the highest value that's less than the nearest integer to your original value. This still displays as the integer when you print it, but that's just rounding; it's really slightly less than the integer. So if it's printing as "4.0", it's really something like 3.9999999999999 or some such.
When you convert the value to an Int, it keeps the integer part and discards the part to the right of the decimal. Since the floating-point value is slightly less than the integer you rounded to thanks to .nextDown, the integer part is going to be one less than that integer.
Solution: Get rid of the .nextDown.
When you cast you lose precession.
In your case the line returns a double: Assume baby age is 9 then startingAge is 3.999999
let startingAge = (Double(babyAge/2).rounded().nextDown)
and when you print it your answer becomes 3
print("\(Int(startingAge))")
To fix this use this line instead:
let startingAge = (Double(babyAge/2).rounded().nextDown).rounded()
This is what nextdown does, it does not round values, and if the number is
a floating point number it becomes slightly less. If the number was to be an int it would become 1 less I presume.

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

Computing UILabel height & UIFont height (for number of lines) using ceil() or roundf()?

I have this values that i've logged:
label.frame.size.height :18.000000, label.font.lineHeight: 17.895000
if i use roundf() like:
roundf(label.frame.size.height / label.font.lineHeight) // answer: 1
while with ceil()
ceil(label.frame.size.height / label.font.lineHeight) // answer: 2
but when computed manually: answer is 1.00586756
I wonder whats the best and more reliable(generally) between this two. Why is everybody using ceil() to determine the number of lines of UILabel?
In the case of number of lines each letter after the limit a line could display should be taken to next line so .005 is also significant this .005 part of the text should carry to next line. So it is better to use ceil() rather than roundf( ). In roundf( ) a value will be significant only when it is greater or equal to its half value)
ceil()
The C library function ceil(x) returns the smallest integer value greater than or equal to x.
I still dont understand why must of the people use ceil() when computing the number of line since roundf() is more accurate..
But when talking about computing for the number of line.. i look to me that 'roundf()' is indeed more accurate, but since its number of lines.. decimal values are not significant..
Computing what is the image:
54 / 17.895000 = 3.01760268
And numberOflines = 3
if we use roundf() answer would be 3 as well
while if ceil() is already 4
therefore using floor() or simply converting the result to int will do the work:
int result = (int)floor(answer);
//or
int result = (int)answer;
About my question, i think roundf() to the work for me for computing number of lines generally..
I'm making a class that will compute the number of line base from this values, and will be used by the whole app.

Resources