objective-c- selecting items from a database based on a slider value? - sql

I am trying to make a basic app that first brings you to a view controller with a slier, at the moment no matter what the slider value is it selects all from the database but I want the slider value to select all where the price is like the slider value.
I added this line to my code:
NSString *sql = [NSString stringWithFormat:#"select * from carPrices where price = %f", slider.value];
but it does not work, I get the error:
implicit conversion of an objective c pointer to 'const char*' is disallowed with ARC
I previously had the line saying const char *sql instead,
Please if anybody knows what I could be doing wrong could they please give me some advice.
EDIT
Ok so I managed to fix the error by adding this line:
NSString *SQLSTMNT = [NSString stringWithFormat:#"select * from carPrices where price = %f", slider.value];
const char * sql =[SQLSTMNT UTF8String];
but as the prices are very specific is there any way to get it to select prices like the one you chose?
Thanks,
MB.

Float values are hard to work with.
You cannot reliably check if two values are the same, so where price = %f is going to fail.
Instead, you need to do check a range of values:
CGFloat min = slider.value - 0.1;
CGFloat max = slider.value + 0.1;
NSString *sql = [NSString stringWithFormat:#"select * from carPrices where price > %f and price < %f", min, max];

Related

Converting decimal number to binary Objective-C

Hi I have made an IOS app that converts binary, hexadecimal and decimal values. It all works fine except for my decimal to binary conversion. Here is what I have. It returns 0s and 1s but far too many. Can anyone tell me why this is or help me with a better method?
NSString *newDec = [display text]; //takes user input from display
NSString *string = #"";
NSUInteger x = newDec;
int i = 0;
while (x > 0) {
string = [[NSString stringWithFormat:#"%u", x&1] stringByAppendingString:string];
x = x>> 1;
++i;
}
display.text = string; //Displays result in ios text box
Try this:
NSUInteger x = [newDec integerValue];
And next time don't ignore the Compiler's "Incompatible pointer to Integer conversion" hint...
Explanation: Afaik, assigning an object to an int, actually assigns the address of the object to that integer, not the content of the string (which is what you want).

How to get a CGFloat from a NSString?

In my current app, I have an equation that typically solves to a pretty long amount of decimal numbers, i.e: 0.12345 or .123 . But the way that I need this to work is to only show say 1 or 2 decimal numbers, so that would essentially produce 0.12 or 0.1 based on the values I mentioned.
In order to do this, I have done the following: Taken my CGFloat to a NSString:
CGFloat eX1 = 0.12345
NSLog(#" eX1 = %f", eX1); //This of course , prints out 0.12345
NSNumberFormatter *XFormatter = [[NSNumberFormatter alloc] init];
Xformatter.numberStyle=NSNumberFormatterDecimalStyle;
Xformatter.maximumFractionDigits=1;
NSString *eX1F = [formatter stringFromNumber:#(eX1)];
NSLog (#"eX1F = %#",eX1F); //This prints out 0.1
But my problem is that I need to keep working with this as a CGFloat after it has been formatted, I have tried taken the string back to a number by doing: numberFromString but the problem is that only works with a NSNumber.
What can I do to format my CGFloat and keep working with it as a CGFloat and not a NSString or NSNumber?
Update I have tried:
float backToFloat = [myNumber floatValue];
but the result is number unformatted : 0.10000 I need those extra 0s out
To convert NSString to a CGFloat you can use floatValue:
CGFloat *eX1rounded = [eX1F floatValue];
But you can round eX1 to eX1rounded directly without using a number formatter,
for example:
CFGloat *eX1rounded = roundf(eX1F * 10.0f)/10.0f;
In any case, you should keep in mind that numbers like 0.1 cannot be represented
exactly as a binary floating point number.
Use stringWithFormat: to round and convert to a string for display purposes:
NSString* str = [NSString stringWithFormat:#"%0.2f", eX1];
You can do the same thing in NSLog, the %0.2f says you want 2 decimal places.
NSLog(#" eX1 =%0.2f", eX1); // this prints "0.12"

Objective-C: Flooring to 3 decimals correctly

I am trying to floor a float value to the third decimal. For example, the value 2.56976 shall be 2.569 not 2.570. I searched and found answers like these:
floor double by decimal place
Such answers are not accurate. For example the code:
double value = (double)((unsigned int)(value * (double)placed)) / (double)placed
can return the value - 1 and this is not correct. The multiplication of value and placed value * (double)placed) could introduce something like: 2100.999999996. When changed to unsigned int, it becomes 2100 which is wrong (the correct value should be 2101). Other answers suffer from the same issue. In Java, you can use BigDecimal which saves all that hassels.
(Note: of course, rounding the 2100.9999 is not an option as it ruins the whole idea of flooring to "3 decimals correctly")
The following code should work:
#include <stdio.h>
#include <math.h>
int main(void) {
double value = 1.23456;
double val3;
val3 = floor(1000.0 * value + 0.0001) * 0.001; // add 0.0001 to "fix" binary representation problem
printf("val3 is %.8f; the error is %f\n", val3, 1.234 - val3);
}
this prints out
val3 is 1.23400000; the error is 0.000000
If there are any residual errors, it comes about from the fact that floating point numbers cannot necessarily be represented exactly - the idea behind BigDecimal and things like that is to work around that in a very explicit way (for example by representing a number as its digits, rather than a binary representation - it's less efficient, but maintains accuracy)
I had to consider a solution involving NSString and it worked like a charm. Here is the full method:
- (float) getFlooredPrice:(float) passedPrice {
NSString *floatPassedPriceString = [NSString stringWithFormat:#"%f", passedPrice];
NSArray *floatArray = [floatPassedPriceString componentsSeparatedByString:#"."];
NSString *fixedPart = [floatArray objectAtIndex:0];
NSString *decimalPart = #"";
if ([floatArray count] > 1) {
NSString *decimalPartWhole = [floatArray objectAtIndex:1];
if (decimalPartWhole.length > 3) {
decimalPart = [decimalPartWhole substringToIndex:3];
} else {
decimalPart = decimalPartWhole;
}
}
NSString *wholeNumber = [NSString stringWithFormat:#"%#.%#", fixedPart, decimalPart];
return [wholeNumber floatValue];
}
For example, the value 2.56976 shall be 2.569 not 2.570
Solution is has simple as that :
double result = floor(2.56976 * 1000.0) / 1000.0;
I don't know why you search complication... this works perfectly, doesn't need to pass by some unsigned int or other + 0.0001 or whatever.
Important note :
NSLog(#"%.4f", myDouble);
Actually do a round on your variable. So it's improper to believe you can floor with a %.Xf

2 text fields to always equal 100 percent xcode

I have two text fields that are for percentages to be entered in. If i put 20 in the first field I would like the second text field to be updated to 60. And later on if I changed the second one to say 30, I would like the first updated to 70.
For ease of showing what I mean, say I have two text fields _firstPercent and _secondPercent with associated labels _firstTotal and _secondTotal:
float firstPercent = [_firstPercent.text floatValue];
float firstAmount = (firstSalePercent / 100) * firstOrigonalAmount;
_firstTotal.text = [NSString stringWithFormat:#"%1.0f",firstAmount];
float secondPercent = [_secondPercent.text floatValue];
float secondAmount = (secondSalePercent / 100) * secondOrigonalAmount;
_secondTotal.text = [NSString stringWithFormat:#"%1.0f",secondAmount];
I really don't know how to handle this so I tried adding this below its respective code. It works for the first one, but not the second.
float percentToSecond = 100 - firstPercent;
_secondPercent.text = [NSString stringWithFormat:#"%1.0f", percentToSecond];
float percentToFirst = 100 - secondPercent;
_firstPercent.text = [NSString stringWithFormat:#"%1.0f", percentToFirst];
I have tried other solutions but don't know what to do.
I would just like someone to lead me in the right direction.
Thanks
How about using the delegate method controlTextDidEndEditing: to see what value was entered, and then set the value for the other text field. In the following code tf1 and tf2 are the IBOutlets for the two text fields.
-(void)controlTextDidEndEditing:(NSNotification *)obj {
float value = [[[obj.userInfo valueForKey:#"NSFieldEditor"] string] floatValue];
if (obj.object == self.tf1) {
self.tf2.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}else if (obj.object == self.tf2) {
self.tf1.stringValue = [NSString stringWithFormat:#"%1.0f",100. - value];
}
}
You'd have to do some more checking to make sure the user didn't enter a number greater than 100 or something not a number.

NSNumber and decimal value

I have an NSNumber like this for example = 1978, i would like to convert this for : 1K9, seconde example : 35700 convert to : 35K7 ( where "k" is kilometers and "M" is meters, how i can do this
thanks
int temp;
NSNumber *yourNumber;//the number you enter from some where
NSString *newValue;
if([yourNumber intValue]>1000){
temp = [yourNumber intValue] % 1000 ;//your number module 1000
newValue= [[temp stringValue]stringByAppendingString:#"K"];
}
Note: I haven't my mac with me, if the [temp stringValue] gives any worning&error please inform me.
Here's how:
NSNumber *initialNumber = [NSNumber numberWithInt:35700];
NSString *resultString = [NSString stringWithFormat:#"%iK%i", floor(initialNumber / 1000), floor((initialNumber % 1000) / 100)];
Basically you can work with the internal number data.
Assuming you are working on a meter-based value, you might want something like this:
NSNumber *sourceValue = ... // your NSNumber value from any source
int meters = sourceValue.intValue;
int km = floor(meters / 1000); // only your kilometers
int sub_km = meters % 1000; // only the part behind the kilometers
int first_sub_km = floor(sum_km / 100); // the first digit of the subrange
NSString *readable = [NSString stringWithFormat:#"%iK%i", km, first_sub_km];
First, you split the meters into <= 1000 and > 1000.
Then you'll just have to put that out formatted, with a K in between.
Write your own subclass of NSNumberFormatter. In this subclass you can implement the calculation logic.
The logic might look like this.
Devide the value by thousend and add your "k"
if you want to have the first digit of hundreds get the thired last digit of your value
return the new string