Convert float to int in Objective-C - objective-c

How can I convert a float to int while rounding up to the next integer? For example, 1.00001 would go to 2 and 1.9999 would go to 2.

float myFloat = 3.333
// for nearest integer rounded up (3.333 -> 4):
int result = (int)ceilf(myFloat );
// for nearest integer (3.4999 -> 3, 3.5 -> 4):
int result = (int)roundf(myFloat );
// for nearest integer rounded down (3.999 -> 3):
int result = (int)floor(myFloat);
// For just an integer value (for which you don't care about accuracy)
int result = (int)myFloat;

Use ceil function:
int intValue = (int)ceil(yourValue);

You can use following C methods to get the int values from different dataTypes.
extern float ceilf(float);
extern double ceil(double);
extern long double ceill(long double);
These functions return float, double and long double respectively. But the job of these function is to get ceil of or floor of the argument. As in http://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Then you can cast the return value to desired type like.
int intVariable = (int)ceilf(floatValueToConvert);
Hope it is helpful.

if we have float value like 13.123 to convert it into integer like 13
Code
float floatnumber=13.123; //you can also use CGFloat instead of float
NSLog(#"%.f",floatnumber); // use for print in command prompt

Related

How to treat a float as an integer bit level in AssemblyScript

I need to implement some C code blow:
float number = 1.5f
long i = * ( long * ) &number;
It is not about to convert the value from float into integer.
This data need to be modified bit level.
Just use reinterpret built-in function:
let num32: f32 = 1.5
let num64: f64 = 2.5
let uint32 = reinterpret<u32>(num32);
// uint32 <- 0x3fc00000
let uint64 = reinterpret<u64>(num64);
// uint64 <- 0x4004000000000000

Return same double only if the double is an int? (no decimals) Obj-C

I'm using a for-loop to determine whether the long double is an int. I have it set up that the for loop loops another long double that is between 2 and final^1/2. Final is a loop I have set up that is basically 2 to the power of 2-10 minus 1. I am then checking if final is an integer. My question is how can I get only the final values that are integers?
My explanation may have been a bit confusing so here is my entire loop code. BTW I am using long doubles because I plan on increasing these numbers very largely.
for (long double ld = 1; ld<10; ld++) {
long double final = powl(2, ld) - 1;
//Would return e.g. 1, 3, 7, 15, 31, 63...etc.
for (long double pD = 2; pD <= powl(final, 0.5); pD++) {
//Create new long double
long double newFinal = final / pD;
//Check if new long double is int
long int intPart = (long int)newFinal;
long double newLong = newFinal - intPart;
if (newLong == 0) {
NSLog(#"Integer");
//Return only the final ints?
}
}
}
Just cast it to an int and subtract it from itself?
long double d;
//assign a value to d
int i = (int)d;
if((double)(d - i) == 0) {
//d has no fractional part
}
As a note... because of the way floating point math works in programming, this == check isn't necessarily the best thing to do. Better would be to decide on a certain level of tolerance, and check whether d was within that tolerance.
For example:
if(fabs((double)(d - i)) < 0.000001) {
//d's fractional part is close enough to 0 for your purposes
}
You can also use long long int and long double to accomplish the same thing. Just be sure you're using the right absolute value function for whatever type you're using:
fabsf(float)
fabs(double)
fabsl(long double)
EDIT... Based on clarification of the actual problem... it seems you're just trying to figure out how to return a collection from a method.
-(NSMutableArray*)yourMethodName {
NSMutableArray *retnArr = [NSMutableArray array];
for(/*some loop logic*/) {
// logic to determine if the number is an int
if(/*number is an int*/) {
[retnArr addObject:[NSNumber numberWithInt:/*current number*/]];
}
}
return retnArr;
}
Stick your logic into this method. Once you've found a number you want to return, stick it into the array using the [retnArr addObject:[NSNumber numberWithInt:]]; method I put up there.
Once you've returned the array, access the numbers like this:
[[arrReturnedFromMethod objectAtIndex:someIndex] intValue];
Optionally, you might want to throw them into the NSNumber object as different types.
You can also use:
[NSNumber numberWithDouble:]
[NSNumber numberWithLongLong:]
And there are matching getters (doubleValue,longLongValue) to extract the number. There are lots of other methods for NSNumber, but these seem the most likely you'd want to be using.

Converting GPS coordinates (latitude and longitude) to decimal

I am getting the latitude and longitude from GPS device. They look like 21081686N,079030977E
If I manually convert them to 21°08'16.86"N, 79°03'09.77"E and check on Google maps, the location is almost correct.
How do I convert these values in java and convert them to decimal accurately? Any JAVA libraries?
Thanks,
You shouldn't need a library, but rather just break up the strings into their component parts. Perhaps this will help. Please note I'm not a Java programmer so this syntax could very well be wrong. (Perhaps retag your question to Java)
By decimal I presume you mean decimal degrees and not ddd.mmss
// Object for Lat/Lon pair
public class LatLonDecimal
{
public float lat = 0.0;
public float lon = 0.0;
}
// Convert string e.g. "21081686N,079030977E" to Lat/Lon pair
public LatLonDecimal MyClass::convert(String latlon)
{
String[] parts = latlon.split(",");
LatLonDecimal position = new LatLonDecimal();
position.lat = convertPart(parts[0]);
position.lon = convertPart(parts[1]);
return position;
}
// Convert substring e.g. "21081686N" to decimal angle
private float MyClass::convertPart(String angle)
{
while (angle.length() < 10)
angle = StringBuffer(angle).insert(0, "0").toString();
int deg = Integer.parseInt( angle.substring(0,2) );
int min = Integer.parseInt( angle.substring(3,4) );
int sec = Integer.parseInt( angle.substring(5,6) );
int sub = Integer.parseInt( angle.substring(7,8) );
String hem = angle.substring(9);
float value = deg + min / 60.0f + sec / 3600.0f + sub / 360000.0f;
float sign = (hem == "S") ? -1.0 : 1.0; // negative southern hemisphere latitudes
return sign * value;
}

Formatting a float value

In my IPhone App Development, I'm using a timestamp value for an order id value.
I want to format the timestamp value in such a way that it contains only decimal value.
Like
timestamp value= 343434234.78900633
Now I want to format that time stamp value, so that it returns the decimal value 78900633.
You need to use the modf function that breaks a double/float into an int an a fraction.
double intpart;
double param = 343434234.78900633;
double fractpart = modf (param , &intpart);
printf ("%lf = %lf + %lf \n", param, intpart, fractpart);
char buf[32];
sprintf(buf, "%f", fractpart);
int fpart = atoi(buf+2);
printf("Fractional as int = %d\n", fpart);

How do I get the int value from object_getIvar(self, myIntVar) as it returns a pointer

if the variable in object_getIvar is a basic data type (eg. float, int, bool) how do I get the value as the function returns a pointer (id) according to the documentation. I've tried casting to an int, int* but when I try to get that to NSLog, I get error about an incompatible pointer type.
Getting:
myFloat = 2.34f;
float myFloatValue;
object_getInstanceVariable(self, "myFloat", (void*)&myFloatValue);
NSLog(#"%f", myFloatValue);
Outputs:
2.340000
Setting:
float newValue = 2.34f;
unsigned int addr = (unsigned int)&newValue;
object_setInstanceVariable(self, "myFloat", *(float**)addr);
NSLog(#"%f", myFloat);
Outputs:
2.340000
For ARC:
Inspired by this answer: object_getIvar fails to read the value of BOOL iVar.
You have to cast function call for object_getIvar to get basic-type ivars.
typedef int (*XYIntGetVariableFunction)(id object, const char* variableName);
XYIntGetVariableFunction intVariableFunction = (XYIntGetVariableFunction)object_getIvar;
int result = intVariableFunction(object, intVarName);
I have made a small useful macro for fast definition of such function pointers:
#define GET_IVAR_OF_TYPE_DEFININTION(type, capitalized_type) \
typedef type (*XY ## capitalized_type ## GetVariableFunctionType)(id object, Ivar ivar); \
XY ## capitalized_type ## GetVariableFunctionType XY ## capitalized_type ## GetVariableFunction = (XY ## capitalized_type ## GetVariableFunctionType)object_getIvar;
Then, for basic types you need to specify calls to macro (params e.g. (long long, LongLong) will fit):
GET_IVAR_OF_TYPE_DEFININTION(int, Int)
And after that a function for receiving int(or specified) variable type become available:
int result = XYIntGetVariableFunction(object, variableName)
The value that is returned is the value from the right place in the object; just not the right type. For int and BOOL (but not float), you could just cast the pointer to an int or BOOL, since pointers and ints are the same size and they can be cast to each other:
(int)object_getIvar(obj, myIntVar)
It's probably boxing the value in an NSNumber. You can verify this by NSLogging the returned id's className, like so:
id returnedValue = object_getIvar(self, myIntVar);
NSLog(#"Class: %#", [returnedValue className]);
Edit: I found another question just like this one here: Handling the return value of object_getIvar(id object, Ivar ivar)
From my own experimentation, it would appear that my original assumption was incorrect. int and float and other primitives appear to be returned as the actual value. However, it would be appropriate to use ivar_getTypeEncoding to verify that the returned value is the type that you're expecting it to be.
you can use object_getInstanceVariable directly: (haven't tested it)
void *ptr_to_result;
object_getInstanceVariable(obj, "intvarname", &ptr_to_result);
float result = *(float *)ptr_to_result;