简体   繁体   中英

Returning a Formatted NSString From NSNumber?

I have created a database that contains a number of values against other data.

Typically the Number will be in the form of: 40000 or similar. I would like to display this in a form as a NSString like '40,000'.

How would this be best achieved ?

Fritzables

Write a category for NSNumber. Or get a C manual and check at all the ways to format a number in C, which all applies to +NSString stringWithFormat as well.

You can set format like this

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:@"##,##,###"];      
NSString *formattedNumberString = [numberFormatter 
  stringFromNumber:[NSNumber numberWithFloat:1234567]];
NSLog(@"formattedNumberString: %@", formattedNumberString);

尝试这个。

    NSString *formatedString=[NSString stringWithFormat:@"%@",yourValueFromDatabase];

Simply do as follows:

   NSNumber *YourNumber = [NSNumber numberWithInt:123456789];
   NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
   [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
   NSString *FormattedNumber = [formatter stringForObjectValue:YourNumber];
   NSLog(@"value : %@", FormattedNumber);

or

NSString * formatedString = [NSNumber stringValue]; 
  NSString *str = [NSString stringWithFormat:@"%@",yourNumber];

If you want for thousand of records you can use for loop.

Hope this will help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM