Okay so I'm trying to get my values rounded up to the nearest whole number with an IBAction.
So 1.88 -> 2.00 ,
11.40 -> 12.00 ,
111.01 -> 112.00, etc.
-
-(IBAction)roundUp:(id)sender
{
float floatRoundValue=lblTotalRound.text floatValue];
ceilf(floatRoundValue);
NSString *stringRoundValue = [NSString stringWithFormat:#"%1.0f", floatRoundValue];
lblTotalRound.text=stringRoundValue;
}
That's what I got. But it's still rounding down below .5 and to the nearest integer
(Ex. 1.19 -> 1 , i need 1.19 -> 2.00).
I've tried %1.2f but the value doesnt change at all.
What am I doing wrong?
ceilf doesn't modify the value you pass in. It returns a modified value.
floatRoundValue = ceilf(floatRoundValue);
ceilf is a function that returns a value (https://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man3/ceil.3.html) , you simply need to change that line to the following.
floatRoundValue = ceilf(floatRoundValue);
So the complete code would in your case it would be something like this.
-(IBAction)roundUp:(id)sender
{
float floatRoundValue=lblTotalRound.text floatValue];
floatRoundValue = ceilf(floatRoundValue);
NSString *stringRoundValue = [NSString stringWithFormat:#"%1.0f", floatRoundValue];
lblTotalRound.text=stringRoundValue;
}
If you need to have a $ sign before :
-(IBAction)roundUp:(id)sender
{
float floatRoundValue=(lblTotalRound.text floatValue];
floatRoundValue = ceilf(floatRoundValue);
NSString *stringRoundValue = [NSString stringWithFormat:#"$%1.0f", floatRoundValue];
lblTotalRound.text=stringRoundValue;
}
NSString Class Reference
Related
I am making a iphone calculator app and I ran into this issue which I cannot seem to find a solution for.
When user enters numbers I convert them into double and then I convert that double result into a string. I am using %g to get whole numbers. The problem I have is for large numbers it shows a "E" exponent. This is what I have tried so far
NSLog(#"Num1: %g", 5000.0*8.0);
NSLog(#"Num2: %g", 500000.0*85.0);
NSLog(#"Num3: %f", 500000.0*85.0);
NSLog(#"Num4: %.4f", 5000.0*8.0);
NSLog(#"Num5: %.4f", 500000.0*85.0);
NSLog(#"Num6: %g", 5000000.0/3.7);
NSLog(#"Num7: %.4f", 5000000.0/3.7);
This is what I get in terms of results
2013-10-20 14:09:34.261 ECalc[9947:a0b] Num1: 40000
2013-10-20 14:09:34.262 ECalc[9947:a0b] Num2: 4.25e+07
2013-10-20 14:09:34.263 ECalc[9947:a0b] Num3: 42500000.000000
2013-10-20 14:09:34.264 ECalc[9947:a0b] Num4: 40000.0000
2013-10-20 14:09:34.264 ECalc[9947:a0b] Num5: 42500000.0000
2013-10-20 14:09:34.265 ECalc[9947:a0b] Num6: 1.35135e+06
2013-10-20 14:09:34.266 ECalc[9947:a0b] Num7: 1351351.3514
Just like a normal calculator I would like to show whole numbers when numbers are multiplied normally. i.e.
Num2 = 42500000
Num7 = 1351351.3514
So here's my question, is there a string format specifier that I can use that will fit both num2 and num7 results? Do I need to use a lot of logic to see if the numbers after dot are zero then truncate them otherwise keep them and use %.4f?
So, here's a quick and dirty solution to what you need.
double num1 = 5000.0*8.0;
double num7 = 5000000.0/3.7;
int decimalPlaces = 4;
if ((int) num1 == num1)
NSLog(#"Num1: %0.0f",num1);
else
NSLog(#"Num1: %0.*f", decimalPlaces, num1);
if ((int) num7 == num7)
NSLog(#"Num1: %0.0f",num7);
else
NSLog(#"Num1: %0.*f", decimalPlaces, num7);
But then you seemed to be concerned with actually being able to split up an NSString as well. So, the first block of code is the direction I recommend. If you're choosing to keep things complicated and stay within NSString throughout your calculator, then you can create a class that will split up an NSString and return to you either the whole number or the number with all its decimals. What I'm giving here is more than you need, but since you're new to iOS, hopefully it'll help you learn, there's a lot more you can do with this too, if you so desire.
-(NSString *)noZeroes:(NSString *)number
{
int i = 0, decimalPos = 0;
//NSRange says {startHere, forThisManyCharacters}
NSRange subRange = {i, 1};
NSString *substr = [number substringWithRange:subRange];
while (i<[number length] && !([substr isEqualToString:#"."]))
{
i++;
NSRange subRange = {i, 1};
substr = [number substringWithRange:subRange];
}
//No decimal point in this number
if (i == [number length])
return number; //so return the number as is
decimalPos = i+1;
NSRange decimalRange = {decimalPos, [number length] - decimalPos};
NSString *decimals = [number substringWithRange:decimalRange];
NSRange wholeNumRange = {0, decimalPos};
NSString *wholeNums =[number substringWithRange:wholeNumRange];
//Numbers you don't want, you can put anything within a CharacterSet like this
NSCharacterSet *notZeroes = [NSCharacterSet characterSetWithCharactersInString:#"123456789"];
NSRange range = [decimals rangeOfCharacterFromSet:notZeroes];
if (range.location == NSNotFound) {
// nothing but zeroes in the string
return wholeNums;
} else {
// nonzeroes are present
return number;
}
}
You would call this with something like:
NSString *Num1 = #"22345.56"
NSString *truncatedNum1 = [self noZeroes:Num1];
NSLog(#"Num1: %#", truncatedNum1);
I worked a lot in it and can't find a solution. Even the title can't explain clearly.
I have three values weight, quantity and total
I had done the following
float wq = [[weightarray objectAtIndex:selectedint]floatValue];
float q = [quantity floatValue];
float total = wq * q;
for ex, if
[weightarray objectAtIndex:selectedint] = #"3.14";
quantity = 4;
then the result is
wq = 3.140000 q= 4.000000 total = 12.560000
but I need
wq = 3.14 total = 12.56
what to do?
I searched a lot, someone suggests to use NSDecimal,
NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE];
but the scale is not 2 here, wq value may have 3 or four numbers after point.
If the total = 2.30000100 means I need total = 2.300001
how to solve this?
I'm not entirely sure what it is your asking for, but it seems as if you want the values to only display a 2 d.p. In which case you could use a string format like so:
NSString *output = [NSString stringWithFormat:#"float = %.2f", 3.14];
The .2 specifies that the float should be justified to 2 d.p.
Hope this helps
There may be a more direct way to achieve it (which I don't know) but here's a suggestion...
Convert to string as you already do.
Use [myString hasSuffix:#"0"] to see if it ends in zero.
Use [myString substringToindex:[myString length]-1] to create a new string without the final zero.
Repeat.
I know it's not elegant, but unless someone has a better solution, this will at least do what you want.
UPDATE: scratch that - I just discovered [myString stringByTrimmingCharactersInSet:set]. Surely this must be what you need...?
Finally solution found, thanks to Martin
float total = 12.56000;
NSString *s = [NSString stringWithFormat:#"%f", total];
NSLog(#"%#",s);
BOOL success;
success =NO;
while(!success)
{
if ([s hasSuffix:#"0"])
{
s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
}
else if ([s hasSuffix:#"."])
{
s = [s substringWithRange:NSMakeRange(0,[s length]-1)];
success = YES;
}
else
success = YES;
}
NSLog(#"%#",s);
if total = 12.560000 it returns total = 12.56
if total = 12.000000 it returns total = 12
if total = 10.000000 it returns total = 10
if total = 12.3000100 it returns total = 12.30001
I am making a grading App for my students, but my comparison operators are not functioning they way I expect them to. My code is as follows;
float FINAL = ((_gradeyouwant - (_quarter1 * 0.2f) - (_quarter2 * 0.2f) - (_quarter3 * 0.2f) - (_quarter4 * 0.2f) - (_quarterM * 0.1f)) / 0.1f);
NSLog(#"q1 = %.2f", _quarter1);
NSLog(#"q2 = %.2f", _quarter2);
NSLog(#"q3 = %.2f", _quarter3);
NSLog(#"q4 = %.2f", _quarter4);
NSLog(#"qM = %.2f", _quarterM);
NSLog(#"qF = %.2f", FINAL);
NSLog(#"grade = %.2f", _gradeyouwant);
if ((FINAL > 4.3f))
{
[_result setText:[NSString stringWithFormat:#"It is not possible to get your desired grade."]];
}else if ((FINAL > 4.0f))
{
[_result setText:[NSString stringWithFormat:#"You would need to get an A+"]];
}else if ((FINAL > 3.7f))
{
[_result setText:[NSString stringWithFormat:#"You would need to get an A"]];
}else if ((FINAL > 3.3f))
ETC. ETC.
When you look at the output with NSLog, it tells me the correct value of everything. However, if I make it so the FINAL is 4.0, it does not print the correct string. I was figuring that when it got to the FINAL > 4.0, it would not run that line. But it does. What am I doing wrong? Thanks so much in advance!
This is pretty much how floats work. Google it, e.g. http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
The system may not be able to precisely store 4.0. It's more a limitation of your CPU and choice of data types. Using a range may very well work.
I'd use an int and emulate the decimal digits, e.g. GPA * 100.
In my application I have a music player, which plays music with a length of 0:30 seconds.
However in a UILabel I am currently displaying the progress, and as it is a float, the label is displaying i.e 14.765.
I would appreciate it if you could tell me how I could get the label to display
0:14 rather than 14.765.
Also, I would appreciate it if you could tell me how I could display 0:04 if the progress was 4seconds in.
This works properly:
float time = 14.765;
int mins = time/60;
int secs = time-(mins*60);
NSString * display = [NSString stringWithFormat:#"%d:%02d",mins,secs];
Results:
14.765 => 0:14
30.000 => 0:30
59.765 => 0:59
105.999 => 1:45
EDIT
In addition the 'one liner':
float time = 14.765;
NSString * display = [NSString stringWithFormat:#"%d:%02d",(int)time/60,(int)time%60];
You first need to convert your float to an integer, rounding as you wish. You can then use the integer division, /, and remainder, % operations to extract minutes and seconds and produce a string:
float elapsedTime = 14.765;
int wholeSeconds = round(elapsedTime); // or ceil (round up) or floor (round down/truncate)
NSString *time = [NSString stringWithFormat:#"%02d:%02d", wholeSeconds/60, wholeSeconds%60];
The %02d is the format specification for a 2-digits, zero padded, integer - look up printf in the docs for full details.
//%60 remove the minutes and int removes the floatingpoints
int seconds = (int)(14.765)%60;
// calc minutes
int minutes = (int)(14.765/60);
// validate if seconds have 2 digits
NSString time = [NSString stringWithFormat:#"%i:%02i",minutes,seconds];
that should work. Can't test it i'm on Win currently
is there a simple way to round the result of a division to upper integer ?
I would like to have this :
18/20 -> 1
19/20 -> 1
20/20 -> 1
21/20 -> 2
22/20 -> 2
23/20 -> 2
... and so on ...
38/20 -> 2
39/20 -> 2
40/20 -> 2
41/20 -> 3
42/20 -> 3
43/20 -> 3
Must I manager with NSNumberFormatter stuff ?
I didn't success to get an integer value with that and have an integer comparison to do.
Thanks in advance !
int x, y;
int result = (x + (y-1)) / y;
testing:
int n = 20;
for (int i = 1; i <= 50; i++) {
NSLog(#"%d+(%d-1) / %d = %d", i, n, n, (i+(n-1))/n);
}
You use the standard ceil() and ceilf() functions available i math.h
Standard C supports double ceil(double x) and long double ceill(long double x). Perhaps the iPhone has these available? If your data is in integers in the first place, then you'll either have to find a clever trick or convert your ints to doubles first.
NSNumberFormatter is used when converting between numbers and strings. In addition to the c functions on primitives mentioned already, you can use NSDecimalNumber and NSDecimalNumberHandler to perform the calculation and rounding given instances of NSNumber. When in doubt, refer to the documentation. Number and Value Programming Guide
Sample code to divide, round up to the next integer and display the result.
NSDecimalNumber *denominator = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInteger:20] decimalValue]];
NSDecimalNumberHandler *numberHandler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundUp scale:0 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
for (NSInteger counter = 1; counter <= 50; counter++) {
NSDecimalNumber *numerator = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithInteger:counter] decimalValue]];
NSDecimalNumber *result = [[numerator decimalNumberByDividingBy:denominator withBehavior:numberHandler] retain];
NSLog(#"%#/%# -> %d", numerator, denominator, [result integerValue]);
[result release];
}