This question already has answers here:
Convert to Float and Calculate
(3 answers)
What is a fast C or Objective-C math parser? [closed]
(4 answers)
Closed 9 years ago.
I want to convert a string for example
NSString *stringWithNumber = #"3/4"
into a NSNumber.
How is this possible?
You can use an NSEXpression to "calculate" the value. Note that you will have the regular int division problem with "3/4".
NSExpression *expression = [NSExpression expressionWithFormat:#"3.0/4.0"];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
If you are only working with n/m fractions, and you mean to have a number representing the result of the fraction, you can do something like
NSString *fraction = #"3/4";
NSArray *components = [fraction componentsSeparatedByString:#"/"];
float numerator = [components[0] floatValue];
float denominator = [components[1] floatValue];
NSNumber *result = #(numerator/denominator);
NSLog(#"%#", result); // => 0.75
Of course this can easily break in case of malformed strings, so you may want to check the format before performing the above computation.
NOTE
In case the fractions coming in input have a format compatible with native float division, David's answer is definitely sleeker and less clunky than mine. Although if you have an input like #"3/4", it won't work as expected and you definitely need to do something like I suggested above.
Bottom line, you should specify better your requirements.
Related
I am having the same issues as here: Dynamically format a float in a NSString.
I have searched my hardest for the answer but everything I do seems to break it.
I have tried the following code:
cell.distanceLabel.text = [NSString stringWithFormat:#"%#km",[item objectForKey:#"distance"]];
the displayed value should only ever have two decimals but for some reason values between 1.00 and 9.99 display with more than two decimals.
Can anyone help me with what I am doing wrong here?
I believe you have to either use:
NSLog(#"THE LOG SCORE : %f", x);
OR you need to convert the float to a string like this:
NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue];
I am using the following statement to get a float value from table:
NSNumber *f = [NSNumber numberWithDouble:(double)sqlite3_column_double(statement, 0)];
The value in the database is 23.679999999 but I am getting 23.68. I tried numberWithFloat but i got the same result.
Can anyone tell me how to get the value without rounding off?
NSNumber-wrapped-double is not a suitable data type for storing decimal values when all digits must be preserved exactly. Use NSDecimalNumber instead:
unsigned char *c = sqlite3_column_text(statement, 0);
NSNumber *f = nil;
if (c) {
NSString *numStr = [NSString stringWithUTF8String:c];
f = [NSDecimalNumber decimalNumberWithString:numStr];
}
This should preserve all significant digits available in your text representation, as long as you use the native value. Converting to float or double may result in rounding due to differences in representation.
I am trying to multiply three TextField's values which are in numbers. These values can contains decimal places. In multiplication Objective-C does not consider decimal places. For example, if the number was 3.45, it would only multiply by 3 and not with the decimals as well. Might be a basic question but i am stuck and really need help!
Here's the code i'm using so far:
- (IBAction)CalculateSimple:(id)sender {
int sum = [[principal text] intValue] * [[rate text] intValue] * [[loan text] intValue];;
total.text = [NSString stringWithFormat:#"$%d", sum]; }
Use double instead of int:
double sum = [[principal text] doubleValue] *
[[rate text] doubleValue] *
[[loan text] doubleValue];
total.text = [NSString stringWithFormat:#"$%f", sum];
You are using intValue (which returns integer type, thus your calculations are done on integers). You need to use floatValue or doubleValue (depending on your needs).
Also - check int/float/double types, if you don't know them yet.
You transform each of your operands to an intValue. Furthermore your result is also declared as an int variable.
Variables of type int can only store whole numbers.
If you want to work with floating point numbers use an appropriate data type like float or double depending on your desired precision and the size of the value.
Take the documentation on values in Objective-C as a reference.
When you are printing your result you also have to match the placeholder to the data type.
See the String Programming Guide
So with that in mind your method would look like this:
- (IBAction)CalculateSimple:(id)sender {
float sum = [[principal text] floatValue] * [[rate text] floatValue] * [[loan text] floatValue];
total.text = [NSString stringWithFormat:#"$%f", sum];
}
This question already has answers here:
Objective C Issue With Rounding Float
(4 answers)
Closed 9 years ago.
The APP I'm writting must do some financial calculations, basically it's all about credits, debits and the balance. The only problem (so far) is that if I calculate 999999999.99 - 0.00 the result is 1000000000.00. Please, does anyone know why that happens? Here's my code:
NSNumber *totalCredits;
NSNumber *totalDebits;
NSNumber *balance;
self.credits = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
totalCredits = [self.credits valueForKeyPath:#"#sum.amount"];
double totalCreditsDouble = [totalCredits doubleValue];
self.creditLabel.text = [NSString stringWithFormat:#"%1.2f", totalCreditsDouble];
self.debits = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
totalDebits = [self.debits valueForKeyPath:#"#sum.amount"];
double totalDebitsDouble = [totalDebits doubleValue];
self.debitLabel.text = [NSString stringWithFormat:#"%1.2f", totalDebitsDouble];
balance = [NSNumber numberWithFloat:([totalCredits floatValue] - [totalDebits floatValue])];
double balanceDouble = [balance doubleValue];
self.balanceLabel.text = [NSString stringWithFormat:#"%1.2f", balanceDouble];
All the data is stored as Double.
The C type double is generally not very well suited for financial calculations.
Foundation.framework has a good data type for that: NSDecimalNumber. NSDecimalNumber uses a decimal representation and has 36 digits of precision.
http://floating-point-gui.de/ is a good resource to start with. You are trying to store exact values using a datatype which cannot represent them with the accuracy or precision you need.
if the integrity of these calculations is important to you then you need to switch to storing these values in a format which accurately represents them.
In this case a simple solution might be to store all of your currencies in their smallest possible denomination (e.g. cents) as integers (assuming you don't need fractional cents and handle any division carefully and consistently).
This question already has an answer here:
How to convert NSNumber objects for computational purposes?
(1 answer)
Closed 9 years ago.
I have an array:
SomeArray =[[NSMutableArray alloc]initWithObjects:[NSNumber numberWithFloat:50.0],[NSNumber numberWithFloat:120.0],[NSNumber numberWithFloat:200.0],nil];
When I retrieve it:
NSNumber* Target = [SomeArray objectAtIndex:0];
When I NSLog it:
NSLog(#"Target %d",Target);
it return something funky like
2013-06-26 01:47:58.940 KKK[1027:c07] Target 121016880
What is the proper way to do this?? I just need the number in the array to be used as float.
You are retrieving a NSNumber, which is an object.
%d is for logging decimals, which is not your case.
Either you log it with
NSLog(#"Target %#", target);
or you convert it to a float and use %f
NSLog(#"Target %f", [target floatValue]);
And PLEASE don't use capitalized identifiers for variables!
You are asking for a decimal %d in the log and also a primitive type. NSNumber is an object that wraps a primitive type numbers. So you can do like that
NSLog(#"target %f",[Target floatValue]) or NSLog(#"target %#",Target). With the first you are sending a message to the object to unwrap the float value with the latter you are asking for the object description that in this case is the number