XCode not using decimal number, only using whole digit - ios

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];
}

Related

NSDictionary with float value return wrong conversion

I have NSDictionary with floating values, I am trying to get values like this
[[NSDictionary valueForKey:#"some_value"] floatValue];
but looks like value not rounded correctly.
For example:
I have value in dictionary: #"0.35" but after above conversion returns 0.34999999403953552 float value, #"0.15" converts into 0.15000000596046448 etc.
When you are converting value from string to float, it lost its precision so you have to format it again. Please look at below the question you will get the better idea of that.
Make a float only show two decimal places
Converting Dictionary value to float
NSString *str = [dict objectForKey:#"key"];
CGFloat strFloat = (CGFloat)[str floatValue];
Try this code, It will work for you. Tested!
float myFloatValue= 2345.678990;
NSString* formattedNumber = [NSString stringWithFormat:#"%.02f", myFloatValue];
NSLog(#"Changed Float Value:%#",formattedNumber);

Dynamically format a float in a NSString for iOS

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];

How to not show unnecessary zeros when given integers but still have float answers when needed

I have an app I'm developing and one of my features is giving answers in float or double values when needed and an integer when the answer is a whole number
so for example if the answer comes out to 8.52 the answer becomes 8.52 but when the answer is 8 the answer is 8 instead of 8.0000, i don't want it to show all the extra 0s.
- (IBAction) equalsbutton {
NSString *val = display.text;
switch(operation) {
case Plus :
display.text= [NSString stringWithFormat:#"%qi",[val longLongValue]+[storage longLongValue]];
case Plus2 :
display.text= [NSString stringWithFormat:#"%f",[val doubleValue]+[storage doubleValue]];
this code doesn't seem to work
These specifiers are standard IEEE format specifiers, which means that you can do things like %.2f to only show 2 decimal places on a float variable.
You could also convert it into an int, and then use the %d format specifier if you wanted to do it that way.
Here's also Apple's documentation on the subject.
EDIT: Based on your comment on the other post, it looks like you're looking for %g, which will essentially remove the extraneous 0's from floats.
display.text= [NSString stringWithFormat:#"%g",[val doubleValue]+[storage doubleValue]];
I found the answer here: Use printf to format floats without decimal places if only trailing 0s
EDIT Formatting
Here is a way that I did this when I needed to display currency (but whole numbers if the currency was a round number.
First we get the money amount as a string
NSString *earnString = _money.payout.displayableAmount;
NSMutableString *strippedString = [NSMutableString
stringWithCapacity:earnString.length];
//scan the string to remove anything but the numbers (including decimals points)
NSScanner *scanner = [NSScanner scannerWithString:earnString];
NSCharacterSet *numbers = [NSCharacterSet
characterSetWithCharactersInString:#"0123456789"];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
[strippedString appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
//create an int with this new string
int earnInt = [strippedString intValue];
//if the string is less than 100 then we only had "change" so display that amount
if(earnInt < 100){
//Dollar amount is less then dollar display just the cents and the cent symbol
NSString *centString = [NSString stringWithFormat:#"%i¢", earnInt];
earnAmount.text = centString;
//if we have a number evenly divisible by 100 then we have whole dollar amount, display that properly
}else if(earnInt % 100 == 0){
//The amount is exactly a dollar, display the whole number
NSString *wholeDollar = [NSString stringWithFormat:#"$%i", (earnInt/100)];
earnAmount.text = wholeDollar;
//finally if we have a mixed number then put them back together with the decimal in-between.
}else{
//Dollar amount is not exactly a dollar display the entire amount
NSString *dollarString = [NSString stringWithFormat: #"$%0d.%02d", (earnInt / 100), (earnInt % 100)];
earnAmount.text = dollarString;
}
Hopefully this helps you out...
You can try this method call:
[NSString stringWithFormat:#"%.0f", [val doubleValue] + [storage doubleValue]];
Easiest way, is NSNumberFormatter. It will only display the decimal if needed. Example (Swift):
let num1: Double = 5
let num2: Double = 5.52
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = .DecimalStyle
print(numberFormatter.stringFromNumber(NSNumber(double: num1)))
print(numberFormatter.stringFromNumber(NSNumber(double: num2)))
This will print 5 and then 5.52.

Convert NSString with factor (e.g. #"3/4") to NSNumber [duplicate]

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.

ios: NSLog show decimal value

NSNumber *weekNum = [dictionary valueForKey:#"inSeasonFor"];
NSDecimalNumber *newWeekNum = ([weekNum intValue] *2)/4;
NSLog(#"%", [newWeekNum decimalValue]);
How can I divide weekNum*2 by 4 and keep the decimal value and print it?
You mean you want the fractional part as well, right?
NSNumber *weekNum = [dictionary valueForKey:#"inSeasonFor"];
// multiplication by 2 followed by division by 4 is division by 2
NSLog(#"%f", [weekNum intValue] / 2.0f);
//we can also use intfloat to resolve.

Resources