Secure and valid way for converting a "float integer" into a natural integer? - iphone

I have a CGFloat that contains only "integers", in the meaning that it actually wants to represent integers only but due to float inprecision it may happen that it internally has a 23.00000000000000000000000142 or something like that. I try to feed an NSDecimalNumber with clean input, so I need to make sure this is truly a naked integer with no dirt. Well, I think this is a good way, but maybe I am wrong:
NSInteger *intVal = floatVal;
That would just get rid of those fragmental parts at the end of the tale, right? Or is there a more secure way to convert it into a true integer?

If you just want to take the integer part of a float then I believe you can just do the following:
CGFloat myfloat = 23.0000000000142f;
int myInt = (int) myfloat;

Related

How to make a simple division of Double by Int in Swift?

Looking at various posts on this topic but still no luck. Is there a simple way to make division/conversion when dividing Double (or Float) with Int? Here is a simple example in playground returning and error "Double is not convertible to UInt8".
var score:Double = 3.00
var length:Int = 2 // it is taken from some an array lenght and does not return decimal or float
var result:Double = (score / length )
Cast the int to double with var result:Double=(score/Double(length))
What this will do is before computing the division it will create a new Double variable with int inside parentheses hence constructor like syntax.
You cannot combine or use different variable types together.
You need to convert them all to the same type, to be able to divide them together.
The easiest way I see to make that happen, would be to make the Int a Double.
You can do that quite simply do that by adding a ".0" on the end of the Integer you want to convert.
Also, FYI:
Floats are pretty rarely used, so unless you're using them for something specific, its also just more fluid to use more common variables.

NSString - Truncate everything after decimal point in a double

I have a double that I need only the value of everything before the decimal point.
Currently I am using
NSString *level = [NSString stringWithFormat:#"%.1f",doubleLevel];
but when given a value of 9.96, this returns "10". So it is rounding. I need it to return only the "9". (note - when the value is 9.95, it correctly returns the "9" value.)
Any suggestions?
Thank You.
Simply assign the float/double value to a int value.
int intValue = doubleLevel;
Cast that baby as an int.
int castedDouble = doubleLevel;
Anything after the . in the double will be truncated.
9.1239809384 --> 9
123.90454980 --> 123
No rounding, simple truncation.
If you want to keep it as a float:
CGFloat f = 9.99;
f = floorf(f);
there are quite a variety of floor and round implementations.
they have been around since UN*X, and are actually part of those low-level libraries, be they BSD, Posix, or some other variety - you should make yourself familiar with them.
there are different versions for different "depths" of floating point variables.
NSString *level = [NSString stringWithFormat:#"%d",doubleLevel];

Proper Usage and Formatting of a Float in Objective-C (or C)

I have an iPhone app. I am storing a float value, (distance), in my sqlite3 db. (The field in the db is formatted to float) I am able to store float values correctly in the db no problem. However, I can't seem to figure out how to pull the value back out of the db the format and present it correctly. Here is my code for pulling the value out of my db and using it:
NSString *itemDistance = [NSString stringWithFormat:#"%f",[item distance]];
float questionDistance = [itemDistance floatValue];
[item distance] is a float value. I can't get this to work. I get a REALLY long value instead. What am I doing wrong? Any help would be greatly appreciated.
Thank you in advance for your help,
L.
Assuming your -distance method is returning the right value, then this sounds like basic misunderstanding of how floats work in C. Common mistake. Every developer falls into this trap at least once.
Floating point numbers can actually only represent a fairly limited number of values. Specifically, unless you happen to choose a value that is exactly representable as a float, you'll get the nearest value, which will often have many decimal places of data.
The reason for this is because a float is only 32 bits; 4 bytes. Now, how many numbers with decimal points are there between 0..1000000 or 0..1000 or, even, 0..1. Infinite. Floats implement a very finite subset of possible numeric values and do so in a way where the resulting possible values may have many decimal places.
Consider:
printf("%5.18f\n", (float) 2.05);
printf("%5.18f\n", (float) 2.45);
printf("%5.18f\n", (float) 4200.75);
printf("%5.18f\n", (float) 37.89);
printf("%5.18f\n", (float) 1.2);
printf("%5.18f\n", (float) -1.2);
This prints:
2.049999952316284180
2.450000047683715820
4200.750000000000000000
37.889999389648437500
1.200000047683715820
-1.200000047683715820
Those values are as close to the values in the bit of code that a float could represent.
If you need more precision, use a double. More precision than that? Use NSDecimalNumber.
And, if you can, use CoreData. It makes managing this kind of thing a bit more straightforward.
why go round in circles?
NSString *itemDistance = [NSString stringWithFormat:#"%.2f",[item distance]];
float questionDistance = [itemDistance floatValue];
Where the .2 is saying I want 2 decimal places.
Whats the type of of distance? If it is an instance of NSNumber then I dont think the code you wrote will work, try
NSString *itemDistance = [[item distance] stringValue];
float questionDistance = [itemDistance floatValue];
or even
float q=[[item distance] floatValue];

How to safely create an NSInteger from an CGFloat?

I've got an CGFloat but need it as an NSInteger. The float value is like 2.0f, so I don't mind about fractional parts and loosing precision. What's a legal way to convert it into NSInteger without trouble (except the loss of precision, of course)?
NSInteger niceInt = niceCGFloat;
seems too simple, smells buggy. Maybe you can explain?
You want the c function lrintf() which rounds a floating point to a long int.
There's always the risk that 2.0f may actually be 1.9999999999f when represented in binary. Your conversion to int would then lead to 1 instead of 2.
To avoid this, I would add 0.5f to your float value. This would also have the effect of rounding your float, instead of truncating it.
NSInteger niceInt = niceCGFloat + 0.5f;

Converting between types in Objective-C

Being a starting Objective-C developer, and not having the patience to actually do some studying, rather than just diving into things, I ran into the following:
I have a CGFloat, and I want to divide it by something, and use the result as an NSInteger.
Example:
CGPoint p = scrollView.contentOffset; //where p is a CGFloat by nature
NSInteger * myIndex = p.x/468.0;
While compiling, I get the error: "Incompatible types in initialization".
I guess that's because of the mismatch between the CGFloat and the NSInteger.
What should I know to get out of this? Sorry for bothering you.
Two problems. You're using a NSInteger pointer (NSInteger *myIndex). And you'll need a cast to go from float to int. Like so:
NSInteger myIndex = (int)(p.x / 468.0);
NSInteger is not an actual object type. It is a typedef for a primitive integer type. Remove the * and your example should work. As it is now, you're trying to assign the result of your math as a pointer and you're getting that error message.