How do I get a float value from a text field? - objective-c

I've seen others ask similar questions, but none of the answers have worked for me; I get the message "Expected ';' at end of declaration list". Can someone walk me through what I'm supposed to do? (This is my first question here, so I'm sorry if I did something wrong.)

float yourVariable = [yourTextField.text floatValue];
Make sure you add validations to your textfield. If you have any non-numeric it will return 0.
How to convert NSString value #"3.45" into float?
I also gone through following link which says returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.

float floatsample = [sampletextfield.text floatValue];

Do this:
NSNumberFormatter *floatFormatter = [[NSNumberFormatter alloc] init];
[floatFormatter numberFromString:textField.text];
Assuming textField is your textField. Then you can check floatFormatter for a nil NSNumber if it can't parse the string properly.

Related

How to convert NSString "{265, 188}" to {265, 188}

I have a NSString variable that contains "{265, 188}". I want just {265, 188} in a variable. What should I do?
Edit:
The code so far is:
//This I get from some XML so I change this part
NSDictionary* controlConditions =#{#"NSPosition":#"{265, 188}"};
NSString* a=(NSString*)[controlConditions valueForKey:#"AXPosition"];
After all, I need to send this to apple script set _controlid_ to a(variable) where i require it to be {265, 188}
Edit:
The variable controlConditions is taken from an XML that gives the position of a UIelement. The NSDictionary returns "{265, 188}" in a(variable). I need to send {265, 188} to an Applescript to match it to the position of various UIelements to get the right one. Hope this makes the problem clearer.
NSString *value = #"{265, 188}";
CGFloat x, y;
sscanf([value UTF8String], "{%lf, %lf}", &x, &y);
NSPoint point = NSMakePoint(x,y);
NSLog(#"%#", NSStringFromPoint(point));
So why don't you just put the values into a fixed array:
int anIntArray[2] = {265,188};
NSLog(#"anIntArray = %d, %d", anIntArray[0], anIntArray[1]);
prints:
anIntArray = 265, 188
Maybe you want to use some type other than int.
The question is really not clear. However, a string of the form {265, 188} is very possibly the result of a previous call to NSStringFromPoint() on an NSPoint whose x field is 265 and y field is 188.
Do you perhaps want to get the NSPoint value back out of the string? If so, you would pass the string to NSPointFromString().
That would not explain how quote characters actually got into the original string, if they are really there. (Unexpectedly, NSPointFromString() actually does still work with a string which contains quote characters.)

Converting integer into formatted string

How would I format an integer when I convert it to a string? For example:
NSString *date = [NSString stringWithFormat:
#"...somestuff... %+02d00", ...., gmtOffset];
The above does not work properly. What I want is, for example, +0200 to appear. I should think that %+02d would convert my integer 2 into "+02". But it does no happen, I get "+2". Why is this? Am I doing something wrong or is some formatting not supported?
EDIT: I finally got it. Works for both positive and negative numbers and adds the leading zeros. Hope it helps.
NSString *str = [NSString stringWithFormat:#"%+03d00", 2];
NSLog(#"%#", str);
The documentation says, that there is a + as modifier. But I don't know how to exactly place/use it.
http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html
+ The result of a signed conversion shall always begin with a sign ( '+' or '-' ). The conversion shall begin with a sign only when a negative value is converted if this flag is not specified.
Link in apple documentation:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
Yes Adam is right:
NSString *date = [NSString stringWithFormat:
#"%+03d00",2];
NSLog(#"date %#",date);

Prevent scientific notation with NSDecimalNumber output as NSString

I have a problem similar to the one in this question: How to obtain an unformatted string representation of an NSDecimal or NSDecimalNumber? I need to have a number in string format accurately represented as an NSNumber, but this number is converted back to a string in other places, and I can't avoid that. The problem I'm having is that when the number is converted back to a string, the string is in scientific notation in some cases.
NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithString:#"0.0001"];
NSString *s = [dn stringValue]; // s will be #"1E-4"
How can I prevent this number from being displayed in scientific notation?
I am working in a circa 2005 version of GNUstep (possibly v1.11.1 for GNUstep Base), rather than on mac or iPhone, which may account for some of the differences in behavior vs the other question I referenced. I have looked over the base library API and the documentation in my own GNUstep install, but I can't seem to find anything to help.
EDIT 2/7/12:
The question has changed slightly, but the goal is still the same. Originally, I didn't think I was able to control the string output piece, but I can pass the value back as a string. At this point I am attempting to use a formatting string, but I still want to prevent the scientific notation from appearing.
[NSString stringWithFormat:#"%1.14g", [val doubleValue]]
I've chosen to use %g because we would like a specific number of significant digits for the value. If I use %f, I can trim the extra zeros, but the number does not always come out cleanly. 800000000.79 appears as 800000000.7899999600, for example.
Is there a way to get a cleanly formatted number with up to a certain number of significant digits (or decimal places) without displaying scientific notation before that number of digits?
I'm willing to accept C advice as well.
You should check out the NSNumberFormatter
// Create formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // adjust this
NSString *formattedOutput = [formatter stringFromNumber:yourDecimalNumber];
How about getting the the C value (double, int, long, etc.) and then format it as a C string, or as an NSString with stringWithFormat:?
Try printing the number using NSNumberFormatter instead of the stringValue method. It has a lot more options.
(I'm assuming NSNumberFormatter is available on GNUstep)
Use the below methods to avoid scientific exponent notation representation.
Convert Double to String
func getStringFrom(double doubleVal: Double) -> String
{
var stringValue : String = "0.00"
let formatter = NSNumberFormatter()
formatter.usesSignificantDigits = true;
formatter.maximumSignificantDigits = 100
formatter.groupingSeparator = "";
formatter.numberStyle = .DecimalStyle
stringValue = formatter.stringFromNumber(doubleVal)!;
return stringValue
}
Convert String to Double
func getDoubleFrom(textField textField: UITextField) -> Double
{
var doubleValue : Double = 0.0
if let val = textField.text
{
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let finalNumber = numberFormatter.numberFromString(val)
doubleValue = (finalNumber?.doubleValue)!;
}
return doubleValue
}

objective C get Decimal from Json object

I am trying to parse a json value to a decimal with no success. I am using the following framework
http://code.google.com/p/json-framework/
and my code is as follows
NSDecimal RRP = [[jProduct objectForKey:#"Price"] decimalValue];
NSLog(#"%#", RRP);
I get
Program received signal: “EXC_BAD_ACCESS”.
Just to test I thought I would try this:
NSLog(#"%#", [jProduct objectForKey:#"Price"]);
42.545
I get the value but obviously I have not set the NSDecimal.
Anybody else had similar experince or can see what I am doing wrong?
Thanks
I'm not familiar with the framework you are using but I would suggest the following:
What is the type returned by [jProduct objectForKey:#"price"]?
You probably need to work around the fact that this is the wrong type - maybe a an NSString?
Try:
NSDecimal RRP = [[NSDecimalNumber decimalNumberWithString:[jProduct objectForKey:#"Price"] decimalValue];
Edit:
Oh and NSDecimal is a struct, not an object so you shouldn't be using NSLog(#"%#"); as the %# format identifier is for objects.. Instead you can use the basic type format identifiers such as %d or %i and access the components of the structure individually.
However, as you probably want to log a decimal rather than the components of the struct (sign, mantissa etc) then you will probably want to convert it back to an NSDecimalNumber (which is an object).
So it becomes:
NSLog(#"%#", [NSDecimalNumber decimalNumberWithDecimal:RRP]);
[jProduct objectForKey:#"Price"]
may be a NSString. NSString respond to:
– doubleValue
– floatValue
– intValue
– integerValue
– longLongValue
– boolValue
not decimalValue
Verify the class of your data.
store the value in NSNumber
NSNumber *num = [jProduct objectForKey:#"Price"];
An NSDecimal is a struct, not an object. If you want to print an NSDecimal, use NSDecimalString():
NSDecimal rrp = [[jProduct objectForKey:#"Price"] decimalValue];
NSLog(#"%#", NSDecimalString(rrp));
See Decimal & JSON example. I think it will help you.

Cast an Objective C UITextField value to float

I have a UITextField called txtDiscount
It has a value in it: txtDiscount.text == 2.3 //for example
I've tried:
float test = (NSNumber *)txtDiscount.text;
And it compiles, but at runtime breaks down.
Unacceptable type of value for attribute: property = ..."; desired type = NSNumber; given type = NSCFString; value = .
How can I cast the value?
Any help greatly appreciated,
Thanks // :)
You probably want something like:
float test = [txtDiscount.text floatValue];
The NSString documentation provides a list of all the built-in casts.
A cast like this
(NSNumber *)myInstance
is telling the compiler to treat 'myInstance' as if it were an instance of class NSNumber. This may influence compile time warnings and errors. Note: - the compiler. It makes no difference to the code that is generated or run - at all. The code that you are running is still
float test = [txtDiscount text];
where the method -text is returning a pointer to an NSString and you are trying to assign it to a float variable.
see clee's answer for how to get float value from an NSString - but make sure you understand why what you were trying to do is wrong. It will help loads in the long run.