iPhone: How do you truncate a float without rounding? - iphone

I need to simply truncate a floating point number (truncate and not round it).
float FloatNum = 43.6823921;
NSString *numString = [NSString stringWithFormat:#"%.1f", FloatNum]; // yields 43.7

There are many ways you can do, but your solution is going to depends on a number of factors.
This will always truncate to the tenths place.
float floatNum = 43.6823921;
float truncatedFloat = truncf(floatNum * 10) / 10;
As chown mentioned, you can convert it to a string and take the substring. You might want to use rangeOfString: os something to find the decimal if you don't always deal with double digit numbers.
Another option would be to use NSDecimalNumber with it's method decimalNumberByRoundingAccordingToBehavior: to set rounding explicitly. I've used this option a few times to handle currency manipulations where accuracy is very important.
float num = 43.6894589;
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:[[NSNumber numberWithFloat:num] decimalValue]];
float truncatedFloat = [[decimalNumber decimalNumberByRoundingAccordingToBehavior:self] floatValue];
// NSDecimalNumberBehaviors
- (NSDecimalNumber *)exceptionDuringOperation:(SEL)method error:(NSCalculationError)error leftOperand:(NSDecimalNumber *)leftOperand rightOperand:(NSDecimalNumber *)rightOperand {
return [NSDecimalNumber notANumber];
}
- (short)scale {
return 1;
}
- (NSRoundingMode)roundingMode {
return NSRoundDown;
}

This will convert a float to string, get the substring to index 4, the convert back to a float. I think this is the usual way of truncating a float without rounding at all: float myTruncatedFloat = [[[[NSNumber numberWithFloat:43.6823921] stringValue] substringToIndex:4] floatValue];. This will convert 43.6823921 into 43.68.
float myfl = 43.6823921;
NSNumber *num = [NSNumber numberWithFloat:myfl];
NSString *numStr = [num stringValue];
NSLog(#"%#", numStr);
NSLog(#"%#", [numStr substringToIndex:2]);
NSLog(#"%#", [numStr substringToIndex:3]);
NSLog(#"%#", [numStr substringToIndex:4]);
NSLog(#"%#", [numStr substringToIndex:5]);
NSLog(#"%#", [numStr substringToIndex:6]);
NSLog(#"%#", [numStr substringToIndex:7]);
NSLog(#"%#", [numStr substringToIndex:8]);
float newMyFloat = [[numStr substringToIndex:4] floatValue];
NSLog(#"%.1f", newMyFloat);
newMyFloat = [[numStr substringToIndex:5] floatValue];
NSLog(#"%.2f", newMyFloat);
Prints:
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68239
[AppDelegate application:didFinishLaunchingWithOptions:]: 43
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.682
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6823
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68239
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.6
[AppDelegate application:didFinishLaunchingWithOptions:]: 43.68

Related

How to convert currency from string format to number format?

I need to convert currency from string format to number format.
For example my string variable value is #"10 lakh". The string value for this converted into number format would be 1000000. How can one make this type of conversion?
(Converting 10 lakh to 1000000, this is the issue)
Try
- (NSNumber *)multiplierForKey:(NSString *)key
{
NSDictionary *dict = #{#"thousand":#1000, #"lakh":#100000, #"million":#1000000, #"crore":#100000000};
NSNumber *value = dict[[key lowercaseString]];
return value?value:#1;
}
- (void)findMultiplier{
NSString *string = #"10 lakh";
NSArray *components = [string componentsSeparatedByString:#" "];
if ([components count]==2) {
NSNumber *value = components[0];
NSString *key = components[1];
NSNumber *multiplier = [self multiplierForKey:key];
NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithDecimal:[value decimalValue]];
NSDecimalNumber *multiplierValue = [NSDecimalNumber decimalNumberWithDecimal:[multiplier decimalValue]];
NSDecimalNumber *finalValue = [decimalValue decimalNumberByMultiplyingBy:multiplierValue];
NSLog(#"Value : %#",finalValue);
}
}
You can make switch cases according to your denominations. By choosing particular switch case you can choose the desired value. I don't think there is predefined method to accomplish this.
hope this helps.

to get float values of latitude and longitude from database

I am trying to get the latitude and longitude of certain regions stored in my database and to store them in an array. I have to store the values as float types. I am getting other values by the following code:
NSString *walkQuery = [[NSString alloc] initWithFormat:#"SELECT Wid,WName,SName,Latitude,Longitude from Walks,SubRegions WHERE Walks.Sid=SubRegions.Sid AND Rid = %d",[regionId integerValue] ];
sqlite3_stmt *walkstatement = nil;
if (sqlite3_prepare_v2(walkNameDB,[walkQuery UTF8String], -1, &walkstatement, nil) == SQLITE_OK)
{
while( sqlite3_step(walkstatement) == SQLITE_ROW )
{
NSNumber *WId;
int temp1 = (int)sqlite3_column_int(walkstatement, 0);
WId = [[NSNumber alloc] initWithInt:temp1];
char *WNameCharacter;
WNameCharacter = (char *) sqlite3_column_text(walkstatement, 1);
NSString *WNameString = [[NSString alloc] initWithUTF8String:WNameCharacter];
char *SNameCharacter;
SNameCharacter = (char *) sqlite3_column_text(walkstatement, 2);
NSString *SNameString = [[NSString alloc] initWithUTF8String:SNameCharacter];
NSMutableDictionary *tempWalk = [[NSMutableDictionary alloc] init];
[tempWalk setObject:WId forKey:#"WalkId"];
[tempWalk setObject:WNameString forKey:#"WalkName"];
[tempWalk setObject:SNameString forKey:#"SubRegionName"];
[regionWalkArray addObject:tempWalk];
Is their any way by which I can get the two float values of latitude and longitude also like I am doing in my code?
Please suggest....
You can use:
float latitude = (float) sqlite3_column_double(walkstatement, 3);
float longitude = (float) sqlite3_column_double(walkstatement, 4);
And can store in dictionary like:
[tempWalk setObject:[NSNumber numberWithFloat:latitude] forKey:#"latitude"];
[tempWalk setObject:[NSNumber numberWithFloat:longitude] forKey:#"longitude"];
You can retrieve it like:
float latitude = [[tempWalk objectForKey:#"latitude"] floatValue];
float longitude = [[tempWalk objectForKey:#"longitude"] floatValue];

Conversion Fahrenheit to celsius programmatically

In my project, want to show the weather in fahrenheit first, then if the user wants clickes on conversion, needs to show the weather in celsius. My code is
NSNumber *metric = [[NSUserDefaults standardUserDefaults] objectForKey:#"metric"];
NSLog(#"Metric is %#", metric);
CGFloat aFloat = [speed floatValue];
CGFloat tFloat = [temperature floatValue];
CGFloat tempFloat = (tFloat-30)/2;
NSNumber * p_Number = [NSNumber numberWithFloat:tempFloat];
//Convert mph to kmph
if ([metric boolValue]) {
[windValueLabel setText:[NSString stringWithFormat:#"%.2f kmph", aFloat * 1.6] ];
temperatureLabel.text = [NSString stringWithFormat:#"%#", p_Number];
}
else{
[windValueLabel setText:[NSString stringWithFormat:#"%.2f mph", aFloat / 1.6]];
temperatureLabel.text = [NSString stringWithFormat:#"%#", temperature];
}
When u start the app, its working and showing temperature in fahrenheit, but crashes at celsius man... is that the current conversion. help me out guys
Your formula is slightly off, you want:
CGFloat tempFloat = (tFloat-32.0) / 1.8;
But that's not what making it crash. In fact, it's not crashing for me. What message do you get when it crashes?

componentsSeparatedByString return wrong result

I used this code to cut the string
NSString *titleString = #"22.225453615805794,113.554006577014889";
NSArray *array = [titleString componentsSeparatedByString:#","];
NSLog(#"title string %#", titleString);
NSLog(#"first %.15f", [[array objectAtIndex:0] floatValue]);
NSLog(#"second %.15f", [[array objectAtIndex:1] floatValue]);
but why it return
22.225454330444336
and
113.554008483886719
Because floating point numbers are not that accurate, you can get a higher accuracy by calling doubleValue instead of floatValue:
NSLog(#"second %.15f", [[array objectAtIndex:1] doubleValue]);
This is not a problem with componentsSeparatedByString:.
I think there is problem in converting string into float. Try using double.

NSString parsing

I need to parse this string into three different components:
Location: 1|#69.83623|#24.432223|#Cupertino, California
The value is stored in one NSString. I need it in three different strings. One string for latitude, one for longitude and one for location.
Any idea how I can do that?
Thanks!
You can use this method to get an array of different components:
NSArray *bits = [locationString componentsSeparatedByString: #"|#"];
Each item in the NSArray will be an NSString.
Try the following
NSString *location = #"1|#69.83623|#24.432223|#Cupertino, California";
NSArray *components = [location componentsSeparatedByString:#"|#"];
NSLog(#"%#",components);
float latitude = [[components objectAtIndex:1] floatValue];
float longitude = [[components objectAtIndex:2] floatValue];
NSString *loc = [components objectAtIndex:3];
NSString *t = #"Location: 1|#69.83623|#24.432223|#Cupertino, California";
NSArray *k = [t componentsSeparatedByString:#"|"];
NSLog(#"components %#", k);