Implementing decimal instead of fraction, Calculator Xcode App - iphone

Ive scoured everywhere and haven't found a situation similar to mine.. New to Xcode/Objective C, I am putting together a dual purpose (fraction/decimal) calculator app. Ive found some good stuff on the fractions, and have them calculating correctly. However the decimal is a different story. I can get it to appear with this:
-(IBAction) pressDecimal
{
NSRange range = [display.text rangeOfString:#"."];
if ( range.location == NSNotFound ) {
display.text = [display.text stringByAppendingString:#"."];
}
or this:
-(IBAction) pressDecimal
{
[displayString appendString: #"."];
display.text = displayString;
}
The latter works great, to DISPLAY it on the calculator. I try to read it in as a slot, a double, and i just can't seem to read it in properly... here is how i get the digits in:
- (void) workNums: (int) nums
{
currentNumber = currentNumber * 10 + nums;
[displayString appendString:
[NSString stringWithFormat: #"%i", nums]];
display.text = displayString;
}
//uses tags from attribute inspector (decimal tagged 10)
-(IBAction)pressNum:(UIButton *)sendIT
{
int nums = sendIT.tag;
[self workNums: nums];
}
Ive looked everywhere, tried changing from floats to doubles ( i can get it to display 0.00's when i play with them) also here is my method to converting the ANSWER that is a FRACTION to a DECIMAL..which works great too:
- (double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return NAN;
So again, cleanly stated... How may I get Objective C to see the decimal inputed in the app, and display the answer as a decimal properly.. am i screwed because i started this a mainly a fraction calculator? Thanks from a noob that moved from BASIC to Objective C
EDIT 4/27/12 ***
(new to Stack - but please read my comment below.. i am looking to find out why i can't read decimals into my program... I've tried changing from ints (which i know won't work) and doubles and floats, but all i get is 0.00 on user input when running this all as doubles:
-(IBAction)pressNum:(UIButton *)sendIT
{
int nums = sendIT.tag;
[self workNums: nums];
}
- (void) workNums: (int) nums
{
currentNumber = currentNumber * 10 + nums;
[displayString appendString:
[NSString stringWithFormat: #"%i", nums]];
display.text = displayString;
}
So the goal is to be able to CALCULATE a user inputted decimal number...any suggestions on a if/else situation as these numbers build up in an accumulator / and a double for currentNumber and get turned into numerators/denominators later down the line..(which is probably my issue, but it shouldn't be hard, but I'm making it hard, to use a BOOL or something to say, hey..this isn't a fraction, its a decimal - so lets do this - PLEASE HELP!! GOING NUTS!

I may be thinking this is much simpler than it is, but: if you already have a string like #"3.14" in displayString then you can convert that directly to a double:
double doubleValue = [displayString doubleValue];
Would that not be enough to get the double value and perform calculations?

Related

Convert float to float and truncate after two decimal places Objective-C

I have a float var1 = cashInHandAmount = 4.73000002
I simply want as:
var2 = 4.73.
I have tried like this:
NSString *floatString = [NSString stringWithFormat:#"%.02f",cashInHandAmount];//it prints 4.73
[self.editcash setMaxValue:[floatString floatValue]];//but it again sets 4.73000002 why?
can you guys please help me regarding this?
%f simply rounds for the output. Transforming a float value into a string and back does not work, if the exact value (i. e. 4.73) has no representation in the float format. So transforming it back will "round" the stored value 4.73 into the float format, which is obviously 4.730…02.
You should rarely use (binary, IEEE) floats for financial calculating. Financial values (amount of money) is in most cases an integral value of cents, but no float value of dollars (or whatever). Additionally you can think about using NSDecimal and NSDecimalNumber to ensure, that every value with two digits of precision is storable in the format.
Edit:
float f = 4.73000002;
float rounded = roundf(f * 100.0f) / 100.0f;
NSLog(#"%10.10f", rounded);
outputs:
2014-07-01 10:25:48.653 xctest[596:303] 4.7300000191
It is difficult to check, but probably float can not represent 4.73 exactly. The nearest representable value is 4.7300000191. This is what I said: A rounded decimal representation is not always a possible "binary float" representation. You will face that problem with many values.
Try this :
float var1 = 4.73000002;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.maximumFractionDigits = 2; //Set number of fractional digits
NSNumber *num = [NSNumber numberWithFloat:var1];
NSString *roundedNum = [formatter stringFromNumber:num];
DLOG(#"Answer : %#", roundedNum);
If you want truncate all other decimals you can declare a simple method like this:
- (float)sanitizeFloat:(float)value
{
float newValue = [[NSString stringWithFormat:#"%.2f",value] floatValue];
return newValue;
}
and then
float aFloat = 45.070809;
NSLog(#"%f",[self sanitizeFloat:aFloat]);
In your case:
[self.editcash setMaxValue:[self sanitizeFloat:cashInHandAmount]];
The output will be 45.070000
If you're working with monetary amounts that have fixed decimal places, you should always use NSDecimal or NSDecimalNumber - you shouldn't use floats at all, as they are inexact.
You could use:
-[NSDecimalNumber decimalNumberWithString:]
to create your number, and there are many methods for working with NSDecimalNumbers - see Apple's docs or NSDecimalNumber.h for details.

How to convert from text to number integer?

i have input only number from text field and i want to change it to integer. what code should i write in?
just say text field say for 10 and i want to take that 10 = x, x = integer. so if i use it for mathematic process a = x + 1 and display say 11. is there any chance? i hope you understand what i mean. thank you. i think both of you will answer this simple question but i not because im beginner. im a 3d design graphic switch 180 degree become xcode programming. BTW ive tried this before but it cant.
NSInteger number = [[txtBtn text] integerValue];
Edited :
i've got this error, local declaration of 'number' hides instance variable, pointed to number at result = (number * 2) - 1; and i put the code like this.
NSInteger number = [[txtBtn text] intValue];
result = (number * 2) - 1;
i dont know whats wrong.
Are you sure it's a TextField and not a UIButton you are trying to get the integerValue from?
[txtBtn text]
I created a TextField and a UIButton, and implemented your code:
- (IBAction)btnClicked:(id)sender {
NSInteger i = [[inputField text] intValue];
int result = (i*2)-1;
NSLog(#"%i", result);
}
the output results is correct.
ex: type 5, output in console is 9.

How do I get the floatValue Amount of a Currency-Formatted Label?

I have a Label, let's call it currencyFormattedLabel, the value of which was earlier formatted in another method as currency (with currencyFormatter).
Now, I want to use the number equivalent in that Label. However, when i go to get the number, I only get a value of 0.00.
Maybe this will help explain:
float x = [currencyFormattedLabel.text floatValue];
NSLog(#"x = %.2f", x);
So, if the currencyFormattedLabel is $2.00, this method always ends up returning: x = 0.00
What i want is for it to return x = 2.00.
Is there a way to take my currencyFormattedLabel and get the number value of it?
Thanks for any help you can give!
The dollar sign in the NSString is throwing things off. You will have better luck using NSScanner.
NSScanner *scanner = [NSScanner scannerWithString:currencyFormattedLabel.text];
float x;
[scanner scanFloat: &x];
NSLog(#"x = %.2f", x);
You could also use:
float x = [[currencyFormattedTextLabel.text substringFromIndex:1] floatValue];
if you knew the number would always be predceeded by a dollar sign.

Display answer in UITextField?

Lets say I have:
int a = textbox1;
int b = textbox2;
answer = a + b;
How do you get "answer" to display in textbox3? I'm sure this is a very simple question, but believe it or not, I have done a lot of researching and found nothing. If you could please give an example as "Text" and as "numbers with decimals" I would greatly appreciate it!! Thank you in advance!
Use the text property of NSString to get and set it's text. Use intValue method of NSString to convert the string to integer (assuming that the string contains a valid integer). And finally use stringWithFormat to create a string which contains an integer.
Here is the one line code.
textBox3.text = [NSString stringWithFormat:#"%d", [textBox1.text intValue] + [textBox2.text intValue]];
a and b should probably be floats or doubles if you want decimal values. You can try something like this:
double a = [[textBox1 text] doubleValue];
double b = [[textBox2 text] doubleValue];
[textBox3 setText:[NSString stringWithFormat:#"%f", (a + b)]];

How to convert a double to NSInteger?

Very simple question here. I have a double that I wish to convert back to a NSInteger, truncating to the units place. How would I do that?
Truncation is an implicit conversion:
NSInteger theInteger = theDouble;
That's assuming you're not checking the value is within NSInteger's range. If you want to do that, you'll have to add some branching:
NSInteger theInteger = 0;
if (theDouble > NSIntegerMax) {
// ...
} else if (theDouble < NSIntegerMin) {
// ...
} else {
theInteger = theDouble;
}
NSInteger is a typedef for a C type. So you can just do:
double originalNumber;
NSInteger integerNumber = (NSInteger)originalNumber;
Which, per the C spec, will truncate originalNumber.
but anyway, assuming you want no rounding, i believe this should work simply
double myDouble = 10.4223;
NSInteger myInt = myDouble;
edit for rounding: (i'm sure theres a much simpler (and precise) way to do this.. (this also doesn't account for negative numbers or maximum boundaries)
double myDecimal = myDouble - myInt;
if(myDecimal < 0.50)
{
//do nothing
}
else
{
myInt = myInt + 1;
}
NSInteger is a typedef, it's the same as using an int. Just assign the value like:
double d;
NSInteger i = d;
JesseNaugher mentions rounding and I note the OP needs were met with a simple truncate, but in the spirit of full generalisation it's worth remembering the simple trick of adding 0.5 to the double before invoking floor() to achieve rounding. Extending Jonathan Grynspan's comment: NSInteger myInt = floor(myDouble + 0.5); i.e., rounding up in absolute terms. If rounding 'up' means rounding away from zero a more convoluted approach is needed: NSInteger myInt = floor( myDouble + (myDouble < 0.0 ? -0.5 : 0.5) );