Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString format

I have a NSString I am getting from an array. There are multiple string objects in the array. I want to change the format of the string I get from array and display that new formatted string on UILabel. Let me give an example:

String in array: 539000
String I want to display: 5.390.00

Now the problem is that the string I get from array may be 539000, 14200 or 9050. So the string I want to get are: 5.390.00, 142.00, 90.50.

The correct format is to place a **.** before last two digits, again place a **.** before 3 digits from first **.**.

like image 243
Nitish Avatar asked Sep 09 '11 05:09

Nitish


People also ask

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

How do I append to NSString?

Working with NSString. Instances of the class NSString are immutable – their contents cannot be changed. Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.


1 Answers

Try below code it will help

Objective-C

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
[formatter setGroupingSeparator:@"."];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:3];

NSString *input = @"539000";
NSString *output = [formatter stringFromNumber:[NSNumber numberWithDouble:[input doubleValue]]];
NSLog(@"output :: %@",output);// output :: 5.390.00 

Swift3

let formatter = NumberFormatter()
    formatter.groupingSeparator = "."
    formatter.groupingSize = 2
    formatter.usesGroupingSeparator = true
    formatter.secondaryGroupingSize = 3

    let input = 539000
    let output = formatter.string(from: NSNumber.init(value: input))
    print("output :: \(output!)")// output :: 5.390.00 
like image 179
Narayana Avatar answered Oct 25 '22 01:10

Narayana