Round a float up to the next integer in objective C? - objective-c

How can I round a float up to the next integer value in objective C?
1.1 -> 2
2.3 -> 3
3.4 -> 4
3.5 -> 4
3.6 -> 4
1.0000000001 -> 2

You want the ceiling function. Used like so:
float roundedup = ceil(otherfloat);

Use the ceil() function.
Someone did a little math in Objective C writeup here: http://webbuilders.wordpress.com/2009/04/01/objective-c-math/

Just could not comment Davids answer. His second answer won't work as modulo doesn't work on floating-point values. Shouldn't it look like
if (originalFloat - (int)originalFloat > 0) {
originalFloat += 1;
round = (int)originalFloat;
}

Roundup StringFloat remarks( this is not the best way to do it )
Language - Swift & Objective C | xCode - 9.1
What i did was convert string > float > ceil > int > Float > String
String Float 10.8 -> 11.0
String Float 10.4 -> 10.0
Swift
var AmountToCash1 = "7350.81079101"
AmountToCash1 = "\(Float(Int(ceil(Float(AmountToCash1)!))))"
print(AmountToCash1) // 7351.0
var AmountToCash2 = "7350.41079101"
AmountToCash2 = "\(Float(Int(ceil(Float(AmountToCash2)!))))"
print(AmountToCash2) // 7350.0
Objective C
NSString *AmountToCash1 = #"7350.81079101";
AmountToCash1 = [NSString stringWithFormat:#"%f",float(int(ceil(AmountToCash1.floatValue)))];
OR you can make a custom function like so
Swift
func roundupFloatString(value:String)->String{
var result = ""
result = "\(Float(Int(ceil(Float(value)!))))"
return result
}
Called it like So
AmountToCash = self.roundupFloatString(value: AmountToCash)
Objective C
-(NSString*)roundupFloatString:(NSString *)value{
NSString *result = #"";
result = [NSString stringWithFormat:#"%f",float(int(ceil(value.floatValue)))];
return result;
}
Called it like So
AmountToCash = [self roundupFloatString:AmountToCash];
Good Luck! and Welcome! Support My answer!

Related

Round outcome Fraction Apache Math Common

Is it possible to round the fraction, e.g., 3/2 becomes 1+1/2 and 11/2 becomes 5+1/2 that is produced using Apache Common Math?
Attempt
Fraction f = new Fraction(3, 2);
System.out.println(f.abs());
FractionFormat format = new FractionFormat();
String s = format.format(f);
System.out.println(s);
results in:
3 / 2
3 / 2
It looks like what you are looking for is a Mixed Number.
Since I don't think Apache Fractions has this built in, you can use the following custom formatter:
public static String formatAsMixedNumber(Fraction frac) {
int sign = Integer.signum(frac.getNumerator())
* Integer.signum(frac.getDenominator());
frac = frac.abs();
int wholePart = frac.intValue();
Fraction fracPart = frac.subtract(new Fraction(wholePart));
return (sign == -1 ? "-" : "")
+ wholePart
+ (fracPart.equals(Fraction.ZERO) ? ("") : ("+" + fracPart));
}

What is the Modulo function for negative decimals Objective-C?

I need to calculate modulos with decimals that can be negative as well
for example: fmod( -5.2, 3 );
while mod() works with integers, and fmod() (or fmodf()) works well with decimals, fmod() returns wrong results with negative decimals:
ex:
double modulo = fmod (5.2, 3);
NSLog (#"==> %f", modulo);
==> 2.2 // This is correct !!
double modulo = fmod (-5.2, 3);
NSLog (#"==> %f", modulo);
==> -2.2 // This is wrong !! should be 0.8
Is there another mod() in the library or should i write my own decimal negative mod function ?
something like :
if (res = fmod(x,m) < 0) {
res+=m;
}
Thx !
-2.2 is correct and is also -5.2 mod 3. The fmod function is a C function (and therefore also Objective C), so you can find more detail about it by typing man fmod into terminal. When doing fmod it will preserve the sign of the value that you are moding. So to get the mod you want, you will need to check the sign (of either the result, or the value you are passing in) and if it is negative you will need to add the modulo base, in this case 3.
This is the definition of the fmod function:
double
fmod(double x, double y);
Specifically, the functions return the value x-i*y, for some integer i such that, if y is non-zero, the result has the same sign as x and magnitude less than the magnitude of y.
from the OS X man page.
For your purposes, you can do something like this:
#include <math.h>
float f_mod(float a, float n) {
return a - n * floor(a / n);
}
Of course, be careful to check n>0.
f_mod(-5.2f, 2.0f) = 0.8
f_mod(5.2f, 2.0f) = 2.2
Thank you so i ended up writing a wrapper... What i was hopping i could avoid. This works great for me, and, in my opinion, represents the correct mathematical definition of the modulo (not the C implementation). I am sure this function can be optimized,but for clarity i leave it this way:
//--
//-- Modulo
//--
double calcModulo ( double x, double m) {
double res = INFINITY;
if (m==0)
return res ;
double posMod, negMod, posM, posX;
posM = m < 0 ? -m:m;
posX = x < 0 ? -x:x;
posMod = fmod (posX, posM);
negMod = fmod (-posX,posM) + posM;
// pick up the correct res
if ( x >= 0 ){
if (m > 0) {
res = posMod;
} else {
res = -negMod;
}
}else{
if (m > 0) {
res= negMod;
} else{
res= -posMod;
}
}
return res;
}

How to do memcmp() in Swift?

I'm trying to convert some of my code from Objective-C to Swift. One method that I'm having trouble with does a comparison of a CBUUID with an UInt16. This was fairly straight-forward in Objective-C, but I'm having a hard time coming up with a good way to do this in Swift.
Here's the Objective-C version:
/*
* #method compareCBUUIDToInt
*
* #param UUID1 UUID 1 to compare
* #param UUID2 UInt16 UUID 2 to compare
*
* #returns 1 (equal) 0 (not equal)
*
* #discussion compareCBUUIDToInt compares a CBUUID to a UInt16 representation of a UUID and returns 1
* if they are equal and 0 if they are not
*
*/
-(int) compareCBUUIDToInt:(CBUUID *)UUID1 UUID2:(UInt16)UUID2 {
char b1[16];
[UUID1.data getBytes:b1];
UInt16 b2 = [self swap:UUID2];
if (memcmp(b1, (char *)&b2, 2) == 0) return 1;
else return 0;
}
My (untested) version of this method in Swift got much more complicated and I'm hoping that I'm just missing some better ways to use the language:
func compareCBUUID(CBUUID1: CBUUID, toInt CBUUID2: UInt16) -> Int {
let uuid1data = CBUUID1.data
let uuid1count = uuid1data.length / sizeof(UInt8)
var uuid1array = [UInt8](count: uuid1count, repeatedValue: 0)
uuid1data.getBytes(&uuid1array, length: uuid1count * sizeof(UInt8))
// #todo there's gotta be a better way to do this
let b2: UInt16 = self.swap(CBUUID2)
var b2Array = [b2 & 0xff, (b2 >> 8) & 0xff]
if memcmp(&uuid1array, &b2Array, 2) == 0 {
return 1
}
return 0
}
There are two things that seem to complicate things. First, it isn't possible to declare a fixed sized buffer in Swift, so the char b1[16] in ObjC becomes 3 lines in Swift. Second, I don't know of a way to do a memcmp() in Swift with a UInt16. The compiler complains that:
'UInt16' is not convertible to '#value inout $T5'
So that's where the clunky step comes in where I separate out the UInt16 into a byte array by hand.
Any suggestions?
The corresponding Swift code for char b1[16] would be
var b1 = [UInt8](count: 16, repeatedValue: 0)
and for the byte swapping you can use the "built-in" method byteSwapped
or bigEndian.
Casting the pointer for memcpy() is a bit tricky.
The direct translation of your Objective-C code to Swift would be (untested!):
var b1 = [UInt8](count: 16, repeatedValue: 0)
CBUUID1.data.getBytes(&b1, length: sizeofValue(b1))
var b2: UInt16 = CBUUID2.byteSwapped
// Perhaps better:
// var b2: UInt16 = CBUUID2.bigEndian
if memcmp(UnsafePointer(b1), UnsafePointer([b2]), 2) == 0 {
// ...
}
However, if you define b1 as an UInt16 array then you don't need
memcmp() at all:
var b1 = [UInt16](count: 8, repeatedValue: 0)
CBUUID1.data.getBytes(&b1, length: sizeofValue(b1))
var b2: UInt16 = CBUUID2.bigEndian
if b1[0] == b2 {
// ...
}

Using Greatest Common Divisor for a ratio in Objective-C?

I would like to write a method in Objective-C that will result in a text string 'a:b:c:d'. I have four UISteppers (their values are displayed in a label each). I would like the ratio of those four numbers to display in their lowest integer form, including if some are 0.
Eg. a=6, b=4, c=0, d=0
Textstring = 3:2:0:0
I have found various ways of finding the greatest common divisor including http://macscripter.net/viewtopic.php?id=35759. However, I'm really new to iOS, this is my first app after Hello World, and the maths functions and even declaring a method, defining it and calling it are still a mystery.
Can you help out?
I settled for a method that takes the label values and alters the ratio label:
- (void)CalculateRatio {
int temp;
int PRBCs = [self.labelPRBCs.text integerValue];
int FFP = [self.labelFFP.text integerValue];
int u = PRBCs;
int v = FFP;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
int PRBCratio = PRBCs / u;
int FFPratio = FFP / u;
double Plateletratio = [self.labelPlatelets.text doubleValue] / u;
double Cryoratio = [self.labelCryo.text doubleValue] / u;
NSString *returnValue = [NSString stringWithFormat:#"%d : %d : %.1lf : %.1lf", PRBCratio, FFPratio, Plateletratio, Cryoratio];
self.calculatedRatio.text = returnValue;
}
If you can see some syntactical errors, ways to improve this, I'd be happy to hear them.
Cheers.

Rounding with significant digits

In Xcode /Objective-C for the iPhone.
I have a float with the value 0.00004876544. How would I get it to display to two decimal places after the first significant number?
For example, 0.00004876544 would read 0.000049.
I didn't run this through a compiler to double-check it, but here's the basic jist of the algorithm (converted from the answer to this question):
-(float) round:(float)num toSignificantFigures:(int)n {
if(num == 0) {
return 0;
}
double d = ceil(log10(num < 0 ? -num: num));
int power = n - (int) d;
double magnitude = pow(10, power);
long shifted = round(num*magnitude);
return shifted/magnitude;
}
The important thing to remember is that Objective-C is a superset of C, so anything that is valid in C is also valid in Objective-C. This method uses C functions defined in math.h.