I am creating description label in which i want my description label height should be depend on the value rounded from the expression
NSString *description = [dic objectForKey:#"des"];
UIFont *font = [UIFont boldSystemFontOfSize:8];
CGSize desSize = [description sizeWithFont:font];
float hgt = desSize.width / userView.frame.size.width;
i want the value of hgt should be exact number like if value of output is 0.1 then it should give me value of hgt as 1, another like if value of o/p of devision is 3.3 then hgt should become as 4.
Please help me to solve this problem
Use ceil() to round up.
float hgt = ceil(desSize.width / userView.frame.size.width);
you want to use ceil(). that will round the number up to the nearest integral number.
fabs() – Find the absolute value or unsigned value in parentheses.
result = fabs(x); // fabs(-2.5) = 2.5
ceil() – To round up
i = ceil(x); // ceil(3.5) = 4
floor() – find the integer that is below the floating point value.
i = floor(x); // floor(4.2) = 4
pow() – raise a number to the power.
i = pow(x,y); //pow(4,2) = 16
sqrt() – Square root of a number.
i = sqrt(x); // sqrt(16) = 4
exp() – find the expoential value.
Related
I am having an issue with using a float in a UILabel.
float doubleNum;
floatNum = 10 / 20;
cashLabel.text = [[NSString alloc] initWithFormat:#"%f", floatNum];
If I use "floatNum = 10 / 10;" it correctly returns "1.000000000", however, if I put in "floatNum = 10 / 20" it returns "0.0000000". I have tried about everything I know and it does not work. I know it's a dumb mistake, but I can't figure it out.
Happy Holidays. :)
You need to cast one of the integer's to a float.
Try replacing the divisional line with:
float floatNum = (float) 10 / 20;
and you should get the correct answer.
Or if possible just use floats in your division:
float floatNum = 10.0f / 20.0f;
should also work
The issue here is that you are assigning floatNum the result of dividing one INTEGER by another. The result of 10 / 20 is indeed 0 and as a float, it appears as 0.0000000. In order to obtain a proper result, you need to either use a cast type to turn it into a float or add a .0 to one of the numbers. In division, if one of the numbers is a float (which is easily done by just adding a .0 to one of them), the result will be a float as well.
Normally, C performs "integer division" (basically, division without the remainder -- 10/3 is 3R1, so it yields 3).
When you type floatNum = 10/20, it does 10/20 = 0 (remainder 10).
To fix this, you have to tell the program that you're giving it floating point numbers. Try using:
floatNum = 10.0 / 20,
floatNum = 10 / 20.0, or
floatNum = float (10 / 20).
All of those should work.
try floatNum = 10.0f/20.0f (i.e. make sure the calculation is being done with floats rather than ints)
Consider following example to understand how floats work:
float a = 1/120;
float b = 1.0/120;
float c = 1.0/120.0;
float d = 1.0f/120.0f;
NSLog(#"Value of A:%f B:%f C:%f D:%f",a,b,c,d);
Output: Value of A:0.000000 B:0.008333 C:0.008333 D:0.008333
For float variable a : int / int yields integer which you are assigning to float and printing it so 0.0000000
For float variable b: float / int yields float, assigning to float and printing it 0.008333
For float variable c: float / float yields float, so 0.008333
Last one is more precise float. Previous ones are of type double: all floating point values are stored as double data types unless the value is followed by an 'f' to specifically specify a float rather than as a double.
Change your code to:
float floatNum;
floatNum = 10.0f / 20.0f;
cashLabel.text = [[NSString alloc] initWithFormat:#"%f", floatNum];
I am using CorePlot to graph a set of data. Data for my x-axis consists of dates, while data for my y-axis consists of floats (which I then turn into NSNumber). I am getting data from a feed, and the feed returns numbers with a large number of decimals, eg: 0.46673718852844, 4.59392222219, 353.1293012045.
I'm using the following piece of code to properly format y-axis:
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:3];
[numberFormatter setPositiveFormat:#"###0.000"];
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.minorTicksPerInterval = 1;
y.preferredNumberOfMajorTicks = 5;
y.labelFormatter = numberFormatter;
In most cases, everything works fine. However, sometimes it displays the same value at multiple positions along the axis. See image below:
The values are presented correctly, I would just like to avoid unnecessary (0.466) labels. I've even tried to round the numbers to 3 decimals in numberForPlot method:
if(fieldEnum == CPTScatterPlotFieldY)
{
float floatNum = r.value;
floatNum *= 1000;
int intValue = (int) floatNum;
float decimal = floatNum - intValue;
if (decimal > 0.5) {
intValue++;
}
floatNum = intValue /1000.0;
return [NSNumber numberWithFloat:floatNum];
}
but there is no difference in labels.
The preferredNumberOfMajorTicks property tells the labeling algorithm how many tick marks to use. If you want three ticks, set it to 3. You could also increase the maximum number of fraction digits for the number formatter to avoid the rounding issue altogether.
I believe that because you have said that you want 5 major ticks, that is what you are going to get, regardless of how close the y axis values are. If you sense that the values are too close together, you will probably have to adjust your preferredNumberOfMajorTicks property.
In my app that I am using Core Plot, I turned off the automatic axis labeling and I am putting together my own x and y axis labels. It is a bit more work, but i like the flexibility of doing it myself.
What I did here was dynamically set my preferredNumberOfMajorTicks property while the graph is plotted. Since my formatter shows 3 decimal places, I used the following code to change the number of ticks depending on the Y axis range so that the formatter will show a unique value on the axis at each tick. Too many ticks means the decimal places get cut off and there are duplicate values on the Y axis.
CPTXYAxis *y = axisSet.yAxis;
{
y.preferredNumberOfMajorTicks = round([newYRange.length floatValue]/0.001);
}
I hope this helps.
I am developing an app and want to round off values
i.e if the output is 4.8 I want to display 4.8
while if the output is 4.0 , I want to display 4
Also, it would be great if I could precisely round values : as in if value is 4.34 then round to 4.3 while if its 4.37 then round it to 4.4
One way to round floating point values is to just add 0.5 and then truncate the value.
double valueToRound = GetTheValueFromSomewhere();
double roundedValue = (double)((int)(valueToRound + 0.5));
This will round 1.4 down to 1.0 and 1.5 up to 2.0 for example. To round to other decimal places as you mentioned, simply multiply the initial value by 10, or 100, etc. use the same sort of code, and then divide the result by the same number and you'll get the same result at whatever decimal place you want.
Here's an example for rounding at an arbitrary precision.
double valueToRound = GetTheValueFromSomewhere();
int decimalPrecisionAtWhichToRound = 0;
double scale = 10^decimalPrecisionAtWhichToRound;
double tmp = valueToRound * scale;
tmp = (double)((int)(tmp + 0.5));
double roundedValue = tmp / scale;
So, if decimalPrecisionAtWhichToRound is set to 0 as in the above it'll round to the nearest whole integer. 1.4 will round to 1.0. 1.5 will round to 2.0.
If you set decimalPrecisionAtWhichToRound to 1, it would round to the nearest tenth. 1.45 would round to 1.5 and 1.43 would round to 1.4.
You need to first understand how to do rounding on paper, without someone showing you the code to do it. Write down some numbers and figure out how to round them.
To round to a specific decimal position you add half the value of that position and then truncate. Ie, 1.67 + 0.05 = 1.72 then truncate to 1.7.
But there are two tricky things in programming that aren't there when you do it on paper:
Knowing how to truncate -- There are several ways to do it while programming, but they're non-trivial.
Dealing with the fact that floating-point numbers are imprecise. Ie, there is no exact representation of, say, 1.7, but rather the two closest numbers are apt to be something like 1.69998 and 1.700001
For truncating the trick of multiplying the number by the appropriate power of 10 to produce an integer works pretty well. Eg, (1.67 + 0.05) * 10 = 17.2, then convert to int to get 17, then convert back to float and divide by 10 to get 1.7 (more or less). Or (if you're printing or displaying the value) just format the integer number with the decimal point inserted. (By formatting the integer value you don't have to deal with the problem of imprecise floating point representations.)
If you want to suppress trailing zeros it gets a bit trickier and you probably have to actually write some code -- format the number, then scan backwards and take off any trailing zeros up to the decimal point. (And take the decimal point too, if you wish.)
float number=17.125;
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:2];
NSString *temp = [format stringFromNumber:[NSNumber numberWithFloat:number]];
NSLog(#"%#",temp);
double myNumber = 7.99;
NSString *formattedNumber = [NSString stringWithFormat:#"%.*f",
fmod(round(myNumber * 10), 10) ? 1 : 0, myNumber];
I have found multiple ways to set a sliders value based on ints but I need to increment according to a float .1.
float value = [_xSlider value] *.1;
[_xSlider setValue: value/.1];
But I get a large float number not just 0.3.
I found the answer.
I needed to put the number of decimal places I wanted in front of the decimal then act like it was an int, then push the numbers back onto the other side of the decimal.
int value = [_xSlider value] * 10;
[_xSlider setValue: value * .1];
How might I round a float to the nearest integer in Objective-C:
Example:
float f = 45.698f;
int rounded = _______;
NSLog(#"the rounded float is %i",rounded);
should print "the rounded float is 46"
Use the C standard function family round(). roundf() for float, round() for double, and roundl() for long double. You can then cast the result to the integer type of your choice.
The recommended way is in this answer: https://stackoverflow.com/a/4702539/308315
Original answer:
cast it to an int after adding 0.5.
So
NSLog (#"the rounded float is %i", (int) (f + 0.5));
Edit: the way you asked for:
int rounded = (f + 0.5);
NSLog (#"the rounded float is %i", rounded);
For round float to nearest integer use roundf()
roundf(3.2) // 3
roundf(3.6) // 4
You can also use ceil() function for always get upper value from float.
ceil(3.2) // 4
ceil(3.6) // 4
And for lowest value floor()
floorf(3.2) //3
floorf(3.6) //3
The easiest way to round a float in objective-c is lroundf:
float yourFloat = 3.14;
int roundedFloat = lroundf(yourFloat);
NSLog(#"%d",roundedFloat);
Check the manual page for rint()
If in case you want round float value in integer below is the simple method for rounding the float value in objective C.
int roundedValue = roundf(Your float value);
let's do tried and checkout
//Your Number to Round (can be predefined or whatever you need it to be)
float numberToRound = 1.12345;
float min = ([ [[NSString alloc]initWithFormat:#"%.0f",numberToRound] floatValue]);
float max = min + 1;
float maxdif = max - numberToRound;
if (maxdif > .5) {
numberToRound = min;
}else{
numberToRound = max;
}
//numberToRound will now equal it's closest whole number (in this case, it's 1)