Formatting a number in ios - ios

I am trying to find a solution to add zeros in the beginning of the number as per the total input provided.
Example:
Number = 100
Total Number of digits = 3
The kind of format i will like to have is 001,002,003 and so on.
Thanks
I found out the solution for the same. Posting it below:
while (totalNumCopy) {
totalNumCopy = totalNumCopy/10;
noOfDigits++;
}
NSMutableString *thumbName = nil;
if(noOfDigits > 0)
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setFormatWidth:noOfDigits];
[formatter setPaddingCharacter:#"0"];
[formatter setNumberStyle: NSNumberFormatterPadBeforePrefix];
NSString *stringNumber = [formatter stringFromNumber:[NSNumber numberWithInt:i+1]];
thumbName = [NSString stringWithFormat:#"PageThumb%#.png",stringNumber];
[formatter release];
}

the basic string formatter is like this:
NSLog(#"%03d, %03d, %03d", 1, 2, 3);
the result would be:
001, 002, 003
maybe it helps on you.

NSString *myNumber = [NSString stringWithFormat:#"%03d", number];
i think the above code will help you

Related

Convert numbers to currency

I have number 36381129. I need number 36.381,129
I tried this code, but it doesn't work.
int number = 36381129;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
NSString *numberAsString = [numberFormatter stringFromNumber: [NSNumber numberWithInt:number]];
I give this number.
36.381.129,00 $
I think this is BRAZILIAN REAL CURRENCY Format. You have to call this method with your price in float value, and this method returns your string into your format. Like if we pass 123456789, then it will return 123,456,789.00.
//Convert Price to Your Price Format
+(NSString*)convertFormat:(float)value{
NSString * convertedString = [NSString stringWithFormat:#"%.2f", value];
NSString * leftPart;
NSString * rightPart;
if (([convertedString rangeOfString:#"."].location != NSNotFound)) {
rightPart = [[convertedString componentsSeparatedByString:#"."] objectAtIndex:1];
leftPart = [[convertedString componentsSeparatedByString:#"."] objectAtIndex:0];
}
//NSLog(#"%d",[leftPart length]);
NSMutableString *mu = [NSMutableString stringWithString:leftPart];
if ([mu length] > 3) {
[mu insertString:#"." atIndex:[mu length] - 3];
//NSLog(#"String is %# and length is %d", mu, [mu length]);
}
for (int i=7; i<[mu length]; i=i+4) {
[mu insertString:#"." atIndex:[mu length] - i];
//NSLog(#"%d",mu.length);
}
convertedString = [[mu stringByAppendingString:#","] stringByAppendingString:rightPart];
return convertedString;
}
For more details, refer this blog.
Hope, this is what you're looking for. Any concern get back to me.
Welcome to SO. Your question is pretty vague.
Currency formats depend on the user's locale. It's generally better to either use the default locale of the device, or set a locale, and then let the currency formatter create that string that's appropriate for that locale.
If you set up a hard-coded currency format then it will be wrong for some users. (For example in the US we use a "." as a decimal separator and commas as a grouping symbol. In most of Europe they use a comma as a decimal separator and the period as a grouping symbol. Some countries put the currency symbol at the end of a currency amount, and others put it at the beginning.)
You can use this code:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
[formatter setGroupingSeparator:groupingSeparator];
[formatter setGroupingSize:3];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setUsesGroupingSeparator:YES];
and use it this way:
NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithFloat:rev];
This is a generic solution and will work for any country according to their grouping separator
Taken from: https://stackoverflow.com/a/5407103/2082569

Formatting float values in ios

I have weight values, they can be like 75kg and 75.5kg.
I want to have this values two styles: 75kg, 75.5kg, but NOT 75.0kg. How can I do it?
I have this solution, but I not like it
//show difference in 75 and 75.5 values style
NSString *floatWeight = [NSString stringWithFormat:#"%.1f",weightAtThePoint.floatValue];
NSString *intWeight = [NSString stringWithFormat:#"%.0f.0",weightAtThePoint.floatValue];
NSString *resultWeight;
if ([floatWeight isEqualToString:intWeight]) {
resultWeight = [NSString stringWithFormat:#"%.0f",weightAtThePoint.floatValue];
} else {
resultWeight = floatWeight;
}
The best solution would be using a number formatter:
static NSNumberFormatter * numberformatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
numberformatter = [[NSNumberFormatter alloc] init];
[numberformatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberformatter setMaximumFractionDigits:1];
[numberformatter setMinimumFractionDigits:0];
[numberformatter setLocale:[NSLocale currentLocale]];
});
Since the number formatter creation requires some resources is better if you create a single instance.
When you need to print a string just call this:
NSString * formattedString = [numberformatter stringFromNumber: weightAtThePoint];<br>
NSNumberFomatter prints only the decimal number if it is different from 0 and it also helps you in choosing the correct decimal separator by using the current locale on the device.
If you don't like your solution, then take look at my solution
float flotvalue = weightAtThePoint.floatValue;
int reminder = flotvalue / 1.0;
if (reminder==flotvalue) {
NSLog(#"%f",flotvalue); //75KG Solution
}
else {
//75.xx solution
}
Enjoy Coding

Converting NSString number to float

I am having difficulties converting NSString's that have numbers into floats or something more useful.
I have tried the following code:
NSString *mystring = #"123"
int currentBidAmount = [myString integerValue];
No problem there.
Then float
NSString *mystring = #"123.95"
float currentBidAmount = [myString floatValue];
Again, no problem
However when myString has three decimals - I get an inaccurate number. For Example:
NSString *mystring = #"1.123.95"
float currentBidAmount = [myString floatValue];
It prints out: 1
Can someone tell me what I am doing wrong here?
The goal is to have two NSStrings - get their values and add them up for a total amount. So I need more accuracy than just I am getting now.
While you can get an NSString integer or floatValue you should use NSNumberFormatterfor that. Why? The decimal and grouping separator varies between countries and the floatValue code does only account for . as decimal separator. So users with a locale using a , are doomed.
How to:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
float myFloat = [numberFormatter numberFromString:myString].floatValue;
Read up on various settings here: https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/NSNumberFormatter_Class/Reference/Reference.html
you can't put two commas for a float value
this code works fins:
NSString *example = #"13124.4153";
float floatValue = [example floatValue];
NSLog(#"value = %f", floatValue);
Thanks for the help guys. I managed to solve the problem. The issue was the grouping separator. It separated by leaving a space. So this is why I had inaccurate numbers. Now, since I needed all my numbers to stay in this format but change when I was doing calculations (Adding sums together - I wrote a class method that looks like this:
(NSString *)getDisplayAmountStringWithValue: (NSString *)value Currency: (NSString *)currency
{
NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithString:[value stringByReplacingOccurrencesOfString:#"," withString:#""]];
if ([decimalValue isEqualToNumber:[NSDecimalNumber notANumber]]){
decimalValue = [NSDecimalNumber decimalNumberWithString:#"0"];
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:#" "];
[formatter setDecimalSeparator:#"."];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
if ([currency length] > 0){
[formatter setPositivePrefix:[NSString stringWithFormat:#"%#", currency]];
[formatter setNegativePrefix:[NSString stringWithFormat:#"%#-", currency]];
}else {
[formatter setGroupingSeparator:#""];
}
NSString *newNumberString = [formatter stringFromNumber:decimalValue];
return newNumberString;
}
Notice the if statement. I simply remove the space if I don't supply a currency (Which is not needed when adding sums together) - this along with my existing code, works perfectly.
Thanks for all the tips.

How do I delete trailing zeros on floats without rounding in Objective-C?

I need to clear trailing zeros on floats without rounding? I need to only display relevant decimal places.
For example, if I have 0.5, I need it to show 0.5, not 0.500000. If I have 2.58328, I want to display 2.58328. If I have 3, I want to display 3, not 3.0000000. Basically, I need the amount of decimal places to change.
Use the following:
NSString* floatString = [NSString stringWithFormat:#"%g", myFloat];
NSNumberFormatter is the way to go:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.maximumFractionDigits = 20;
NSString *result = [formatter stringFromNumber:#1.20];
NSLog(#"%#", result);
result = [formatter stringFromNumber:#0.00031];
NSLog(#"%#", result);
This will print:
1.2
0.00031

Suppressing unnecessary zeros

I would like to make a string with stringWithFormat from a double value, without the unnecessary zero at the end.
Examples:
[NSString stringWithFormat:#"%.8f",2.344383933];
[NSString stringWithFormat:#"%.8f",2.0];
expected results:
2.344383933
2
Which is the correct format ?
Thank you.
Use NSNumberFormatter
[numberFormatter numberFromString:[NSString stringWithFormat:#"%.8f",0]]
Sample:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSLog(#"1: %#",[numberFormatter numberFromString:[NSString stringWithFormat:#"%.8f",2.344383933]]);
NSLog(#"2: %#",[numberFormatter numberFromString:[NSString stringWithFormat:#"%.8f",2.0]]);
Results:
1: 2.344383933
2: 2
There is a dedicated class for number formatting, NSNumberFormatter:
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 8
print("\(formatter.stringFromNumber(2.344383933))")
print("\(formatter.stringFromNumber(2.0))")
NSNumberFormatter will also bring localization (decimal points, grouping separators).

Resources