samir
samir

Reputation: 4551

NSNumber and decimal value

I have an NSNumber like this for example = 1978, i would like to convert this for : 1K9, seconde example : 35700 convert to : 35K7 ( where "k" is kilometers and "M" is meters, how i can do this

thanks

Upvotes: 0

Views: 1749

Answers (4)

Tharabas
Tharabas

Reputation: 3422

Basically you can work with the internal number data. Assuming you are working on a meter-based value, you might want something like this:

NSNumber *sourceValue = ... // your NSNumber value from any source
int meters = sourceValue.intValue;
int km = floor(meters / 1000);          // only your kilometers
int sub_km = meters % 1000;             // only the part behind the kilometers
int first_sub_km = floor(sum_km / 100); // the first digit of the subrange
NSString *readable = [NSString stringWithFormat:@"%iK%i", km, first_sub_km];

First, you split the meters into <= 1000 and > 1000. Then you'll just have to put that out formatted, with a K in between.

Upvotes: 1

Simon Germain
Simon Germain

Reputation: 6844

Here's how:

NSNumber *initialNumber = [NSNumber numberWithInt:35700];
NSString *resultString = [NSString stringWithFormat:@"%iK%i", floor(initialNumber / 1000), floor((initialNumber % 1000) / 100)];

Upvotes: 2

Pyth0n
Pyth0n

Reputation: 367

Write your own subclass of NSNumberFormatter. In this subclass you can implement the calculation logic.

The logic might look like this.

  1. Devide the value by thousend and add your "k"
  2. if you want to have the first digit of hundreds get the thired last digit of your value
  3. return the new string

Upvotes: 0

ilhan &#231;etin
ilhan &#231;etin

Reputation: 383

  int temp;
    NSNumber *yourNumber;//the number you enter from some where
    NSString *newValue;

    if([yourNumber intValue]>1000){
        temp = [yourNumber intValue] % 1000 ;//your number module 1000
        newValue= [[temp stringValue]stringByAppendingString:@"K"];

    }

Note: I haven't my mac with me, if the [temp stringValue] gives any worning&error please inform me.

Upvotes: 2

Related Questions