ios: NSLog show decimal value - ios

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.

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

Split double-digit NSInteger into Two NSIntegers

I am trying to figure out how to take a double-digit NSInteger on iOS (like 11) and turn it into 2 separate NSIntegers, each looking like "1". It will always be just 2 digits in the NSInteger, no more, no less, and no decimals.
You can simply use integer/modulo arithmetic
int tensDigit=originalNumber / 10;
int onesDigit=originalNumber % 10;
NSInteger a=11;
NSInteger b=a%10;
NSInteger c=(a-b)/10;
NSLog(#"%# %# %#",a,b,c);
You can simply divide by 10 and find the reminder of division by 10.
NSNumber* number = [NSNumber numberWithInt:21];
NSNumber* partOne = [NSNumber numberWithInt:([number integerValue] / 10)];
NSNumber* partTwo = [NSNumber numberWithInt:([number integerValue] % 10)];
for 21, partOne will be 2 and partTwo will be 1.
In general, for any number n, ith digit is n % pow(10, i)
use this it work (In Swift).
var number = 36
var tenPlace = number / 10
var UnitPlace = number % 10
see the Screen shot.

XCode not using decimal number, only using whole digit

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

iOS - Operations with double values [duplicate]

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).

Isn't NSDecimalNumber supposed to be able to do base-10 arithmetic?

NSDecimalNumber *minVal = [NSDecimalNumber decimalNumberWithString:#"0.0"];
NSDecimalNumber *maxVal = [NSDecimalNumber decimalNumberWithString:#"111.1"];
NSDecimalNumber *valRange = [maxVal decimalNumberBySubtracting:minVal];
CGFloat floatRange = [valRange floatValue];
NSLog(#"%f", floatRange); //prints 111.099998
Isn't NSDecimalNumber supposed to be able to do base-10 arithmetic correctly?
Yes, NSDecimalNumber operates in base-10, but CGFloat doesn't.
Yes, NSDecimalNumber is base-10.
Converting to a floating point type will can loose accuracy. In their case since the example just used NSLog just NSLog the NSDecimalNumber:
NSDecimalNumber *minVal = [NSDecimalNumber decimalNumberWithString:#"0.0"];
NSDecimalNumber *maxVal = [NSDecimalNumber decimalNumberWithString:#"111.1"];
NSDecimalNumber *valRange = [maxVal decimalNumberBySubtracting:minVal];
CGFloat floatRange = [valRange floatValue];
NSLog(#"floatRange: %f", floatRange);
NSLog(#"valRange: %#", valRange);
NSLog output:
floatRange: 111.099998
valRange: 111.1
OK, just doing that CGFloat aNumber = 111.1; shows as 111.099998 in the debugger, even before any operation has been performed on it. Therefore the precision is lost right when it is assigned to the less precise data type, regardless of any arithmetic operations occurring later.

Resources