Produce leading zero with NSNumberFormatter for Currency - ios

for number, after formatting, I hope it show as $050, below code does not work. But If I use NSNumberFormatterDecimalStyle, it can show 050. Do you know why?
NSNumberFormatter *f = [[NSNumberFormatter alloc] init] ;
f.numberStyle = NSNumberFormatterNoStyle;
NSNumber *myNumber;
NSString *myString;
myNumber = [f numberFromString:#"50"]; // Note that the extra zeros are useless
[f setNumberStyle:NSNumberFormatterCurrencyAccountingStyle];
[f setFormatWidth:3];
//[f setPaddingPosition:NSNumberFormatterPadAfterPrefix];
[f setPaddingCharacter:#"0"];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);

The boring answer is that US currency style (and Australian and Canadian, as far as I know) never uses leading zeroes, unless the amount is zero dollars and some cents (e.g. "$0.43"). The NSNumberFormatterDecimalStyle, on the other hand, can use padding zeroes.

Related

NSNumberFormatter with number style NSNumberFormatterCurrencyStyle trouble with commas

I'm trying to do things right with input expenses on some items. So, when working on a device using a locale that uses comma separated decimals (the decimal pad automatically sets comma ',' instead of dot '.' for the user to input) I store the value using core data in a double variable converting the text this way:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMaximumFractionDigits:2];
NSNumber * gasto = [f numberFromString:(((UITextField*) [cell viewWithTag:11]).text)];
destino.nuevaTrans.gasto = [gasto doubleValue];
//destino.nuevaTrans is the managed object, nothing weird there, just storing the decimal value
But when taking the value out of the stored objects and showing them in a table view I'm losing the decimals because of the comma separated locale settings (?). Doing it this way:
etiq = (UILabel*) [cell.contentView viewWithTag:12];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
etiq.text = [numberFormatter stringFromNumber:#(trans.gasto)];
//debugging console output:
//remmember, trans.gasto is only a double
NSLog(#"a: %f, b: %#", trans.gasto ,[numberFormatter stringFromNumber:#(trans.gasto)]);
The output on the simulator that is using dot '.' locale settings works fine, but when deploying on the device that is using comma ',' settings the NSNumberFormatter doesn't seem to translate it correctly to currency style.
//output on the simulator:
2014-09-07 15:00:47.561 iSpend[3930:60b] a: 2.990000, b: $2.99
//output on the device:
2014-09-07 15:02:40.005 iSpend[1389:60b] a: 2.170000, b: ₡2
So, I could try and hack this thing out... But I'm looking for a better programming practice here. Every suggestion is appreciated! Thanks!
Each Locale determines if it shows cents or just Krona. So, if you want to force it to show digits after the comma, add the line:
[numberFormatter setMinimumFractionDigits:2];
to get two digits after comma.
But the example you show has correct output.
u can try to set separator clearly: [formatter setDecimalSeparator:#"."];

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.

Converting double to string return strange value in objective c

I have an NSDictionary which consist of multiple key/pair values. One of them consist double value.
NSNumber *goalValue = [info objectForKey:#"goalValue"];
I put breakpoint and I found that goalValue store the normal value that I need.
and just below I convert it to NSSting like
NSString *stringValue=[goalValue stringValue];
and this stringValue store very strange value.
Guys please help me. I am totally puzzled, I did goggle but nothing change. Please help me. Thanks in advance.
The method stringValue will convert the NSNumber to string by internally calling descriptionWithLocale: with locale as nil and this method in turn will call initWithFormat:locale:,
From Apple docs,
To obtain the string representation, this method invokes NSString’s initWithFormat:locale: method, supplying the format based on the type the NSNumber object was created with:
So format specifier used for double is %0.16g(i.e. 16 digit precision) hence the value 98.09999999999999
I'd suggest using NSNumberFormatter,
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2]; //2 decimal places, change this as required.
NSString *string = [numberFormatter stringFromNumber:goalValue];
Hope that helps!
To prevent this behavior, I suggest using NSDecimalNumber (also this is from my experience best format when dealing with very precise amounts)
NSDecimalNumber *doubleDecimal = [[NSDecimalNumber alloc] initWithDouble:[info objectForKey:#"goalValue"]];
for two digits formatting, use numberFormatter
NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setMinimumFractionDigits:2];
[nf setMaximumFractionDigits:2];
NSString *stringValue = [nf stringFromNumber:doubleDecimal]
Its showing the rounded value so you can round the value to single digit using NSNumberFormatter.
NSNumberFormatter *fomatter = [[NSNumberFormatter alloc] init];
[fomatter setMaximumSignificantDigits:2];
NSString *stringValue=[fomatter stringFromNumber:goalValue];

NSNumberFormatter to add and remove decimals

what is the best way on how to deal with integers, NSStrings and NSNumberFormatter ?
I have an app with an UITextField, where users can input numbers. By every change in the UITextField, my app is immediately taking the input, put it in my function that makes a calculation, and outputs the result in an UILabel.
people can work with large numbers here, so in order to make it easier for them to read what their input is, I decided that I want to make it possible so that the input changes as soon as they insert it.
For example, when you type in 1000 that it automatically changes into 1,000. when you type in 100000000000 it automatically changes into 100,000,000,000 etc.
This I was able to do myself, like this:
formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
self.inputField.text = [formatter stringFromNumber:[formatter numberFromString:self.inputField.text]];
maybe not the best way, but it works.
my function expects an int as input, so up till 999 it's very easy: i can do the following:
[self.inputField.text integerValue];
and it works
but whenever I have 1000 or higher in my UITextField, self.inputField.text property will be 1,000 .. and then things go wrong with using the integerValue from it.
So my question is, how can I go back from NSString to an int, when there are decimals in it ?
Use the -numberFromString function to get an NSNumber from the string, then use the intValue from the NSNumber class to get the integer value:
NSString *string = #"1,000";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number = [formatter numberFromString:string];
int intValue = [number integerValue];// intValue = 1000

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