Objective c string formatter for distances

后端 未结 7 1905
借酒劲吻你
借酒劲吻你 2021-02-02 01:45

I have a distance as a float and I\'m looking for a way to format it nicely for human readers. Ideally, I\'d like it to change from m to km as it gets bigger, and to round the n

7条回答
  •  無奈伤痛
    2021-02-02 02:31

    Yes you need to write your own formatter, like

    #include 
    NSString* convertDistanceToString(float distance) {
        if (distance < 100)
           return [NSString stringWithFormat:@"%g m", roundf(distance)];
        else if (distance < 1000)
           return [NSString stringWithFormat:@"%g m", roundf(distance/5)*5];
        else if (distance < 10000)
           return [NSString stringWithFormat:@"%g km", roundf(distance/100)/10];
        else
           return [NSString stringWithFormat:@"%g km", roundf(distance/1000)];
    }
    ...
    NSLog(@"The distance is %@", convertDistanceToString(1024));
    

提交回复
热议问题