1

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

WrightsCS
  • 50,551
  • 22
  • 134
  • 186
  • You know, of course, that a decimal fraction does not "map" to feet/inches, but rather (for 2 digits) feet and hundredths. And even if the value is valid feet/inches to start with, reading as a float and then "reconstituting" it as you're doing could cause rounding errors if you're not careful. – Hot Licks Nov 17 '14 at 02:37
  • I know that a decimal number does not map into height measurements, thank you. – WrightsCS Nov 17 '14 at 03:19
  • Do you understand the rounding problem? – Hot Licks Nov 17 '14 at 03:21

3 Answers3

2

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.
zaph
  • 111,848
  • 21
  • 189
  • 228
2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

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"
Evan
  • 750
  • 7
  • 13