Objective-C: Separate number right/left of decimal

525 views Asked by At

I am trying to separate the left and right numbers from a float so I can turn each into a string. So for example, 5.11, I need to be able to turn 5 into a string, and 11 into another string.

// from float: 5.11
NSString * leftNumber  = @"5";
NSString * rightNumber = @"11";

From this, I can turn 5.11 into 5' 11".

3

There are 3 answers

0
zaph On BEST ANSWER

One way:

  1. Use stringWithFormat to convert to string "5.11".
  2. Use componentsSeparatedByString to seperate into an array of "5" and "11".
  3. Combine with stringWithFormat.
0
Evan On

You could use a number formatter as such

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.decimalSeparator = @"'";
formatter.positiveSuffix = @"\"";
formatter.alwaysShowsDecimalSeparator = true;
NSString *numberString = [formatter stringFromNumber:@(5.11)];

// Output : 5'11"
0
Sergey Kalinichenko On

You could use NSString stringWithFormat and math functions for that:

float n = 5.11;
NSString * leftNumber  = [NSString stringWithFormat:@"%0.0f", truncf(n)];
NSString * rightNumber = [[NSString stringWithFormat:@"%0.2f", fmodf(n, 1.0)] substringFromIndex:2];
NSLog(@"'%@' '%@'", leftNumber, rightNumber);

However, this is not ideal, especially for representing lengths in customary units, because 0.11 ft is not 11 inches. You would be better off representing the length as an integer in the smallest units that you support (say, for example, 1/16-th of an inch) and then convert it to the actual length for display purposes. In this representation 5 ft 11 in would be 5*12*16 + 11*16 = 1136.