How to format and print float numbers on iOS? - cocoa-touch

I would like to create a formatted output of a floating point number with correct localization on Cocoa-Touch. The output should be equivalent to that of printf("%<a>.<b>f", n), where <a> is the total number of digits and <f> is the maximum number of fractional digits.
Setup of NSNumberFormatter with <a>=6 and <f>=2: (Platform is iOS 5.1 SDK, Xcode 4.3.3 and the iPhone Simulator 5.1)
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterDecimalStyle];
[nf setPaddingCharacter:#" "];
[nf setUsesGroupingSeparator:NO];
[nf setLocale:[NSLocale autoupdatingCurrentLocale]];
[nf setUsesSignificantDigits:YES];
[nf setMaximumSignificantDigits:6];
[nf setMaximumFractionDigits:2];
[nf setRoundingMode:NSNumberFormatterRoundFloor];
NSLog(#"Test: %#", [nf stringFromNumber:[NSNumber numberWithDouble:2.64324897]]);
Expected output (with German locale): Test: 2,64
Observed output (with German locale): Test: 2,64324
Other observations:
I have tried to use different values for the fraction digits, e.g. [nf setMaximumFractionDigits:4] or [nf setMaximumFractionDigits:0]. The result is unchanged, it appears that the fraction digits are ignored. Changing the locale to US only changes the , to a ., not the number of fraction digits.
Question: How can I translate the printf-format string correctly to an NSNumberFormatter?

Ryan is not totally wrong. Use the localizedStringWithFormat method:
using objective-c
NSNumber *yourNumber = [nf numberFromString:yourString];
//to create the formatted NSNumber object
NSString *yourString = [NSString localizedStringWithFormat:#"%.2F", yourNumber];
//to create the localized output
using SWIFT 3
let yourString: String
yourString = String.localizedStringWithFormat("%.2F", yourDoubleNumber) //no need for NSNumber Object
A little bit late but it still might help. Good luck!

Related

How can I configure NSNumberFormatter to display a decimal part without leading zeros?

I’m using NSNumberFormatter to format an NSDecimalNumber.
What configuration can I use to display the number 0.012676 as 1?
Important: I am not trying to round up to 1.0 — I’m trying to round to the hundred place in the decimal, and then strip the preceding zeros and decimal separator.
My current configuration looks something like this:
// in a method...
NSDecimalNumber *value = /* retrieve a value like 0.012676 */;
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
// this is the rounding behavior I want
[nf setRoundingMode: NSNumberFormatterRoundHalfEven];
[nf setMinimumFractionDigits: 2];
[nf setMaximumFractionDigits: 2];
return [nf stringFromNumber: value];
which generates an output of:
.01
With thanks to dasblinkenlight and Twitter friends, the solution is simply to multiply by 100, and then eliminate the fraction digits:
[nf setMultiplier: [NSNumber numberWithInt: 100]];
[nf setMinimumFractionDigits: 0];
[nf setMaximumFractionDigits: 0];
You can eliminate N leading zeros by multiplying by the N-th power of ten. Since you are looking for the hundredth place, multiply 0.012676 by 100, and convert it to an integer.

NSNumberFormatter, appending decimal to calculator from UI

Ok, so I am writing a calculator app now. So far, I'm not having much luck in regard to decimals (my most recent approach hasn't worked well).
-(void) DecimalAdded
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setAlwaysShowsDecimalSeparator:YES];
[formatter setGeneratesDecimalNumbers:YES];
[formatter setDecimalSeparator:#"."];
//first convert the float value of CN into NSnumber
NSNumber *nextstepNumFromCNF= [NSNumber numberWithFloat:currentNumber];
//now we have to convert that number into a string
NSString *CNconverted = [formatter stringFromNumber:nextstepNumFromCNF];
NSNumber *CNdecmAddedAndReadyForPars = [formatter numberFromString:CNconverted];
currentNumber = currentNumber*10 + [CNdecmAddedAndReadyForPars floatValue];
CalculatorScreen = [NSMutableString stringWithFormat: #"%#", CNconverted];
I can append the string to the Calculator screen I can say the number is 1, I see "1." as I'm typing. However this is usually converted to 1 during th float conversion (which is correct).
What is this best way to accomplish this?

NSNumberFormatter iOS big double value

I have a problem formatting big numbers.
I first format a string to a number and since i need to save a string, i get the stringValue from it:
formatter = [[NSNumberFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesSignificantDigits:NO];
[formatter setMaximumFractionDigits:6];
[formatter setMinimumFractionDigits:0];
[formatter setGroupingSeparator:#""];
value = [formatter numberFromString:textField.text];
label = [value stringValue]
and everything is ok, i.e. if i enter 123456745678592.6, i'll get 123456745678592.6.
Then i've to format the string because of different locale:
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setGroupingSeparator:#""];
[numberFormatter setUsesSignificantDigits:NO];
[numberFormatter setMinimumFractionDigits:0];
[numberFormatter setMaximumFractionDigits:6];
tempString = myNumberString;
NSLog(#"number: %#",[NSNumber numberWithDouble:[tempString doubleValue]]);
tempString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[tempString doubleValue]]];
NSLog(#"string translated: %#",tempString);
and i get this:
"number: 123456745678592.6"
"string translated: 123456745678593"
This rounding happens when the significative digits are greater than 15.
Let's say i enter:
12345674567859.2
i then get the right number, i.e.
"number: 12345674567859.2"
"string translated: 12345674567859.2"
with:
12345674567859.23
i get:
"number: 12345674567859.23"
"string translated: 12345674567859.2"
but with:
1234567456785921
i get this:
"number: 1234567456785921"
"string translated: 1234567456785920"
Is this an intrinsic limit of the nsnumberformatter, because the documentation says nothing about this, or i'm doing something wrong?
Could you check what is the actual class of the number? Is it NSNumber or NSDecimalNumber?
A NSNumber is backed up by a double and cannot hold more than 15 significant decimal digits. On the other hand, NSDecimalNumber uses decimal arithmetics and can hold up to 32 significant digits.
I have already learned that NSDecimalFormatter cannot format NSDecimalNumbers correctly (see iOS: formatting decimal numbers).
But maybe it can create a NSDecimalNumber correctly from a string.
I think the problem is not in the limit of the NSNumberFormatter, it´s in the limit of the double itself.
The max value of a double in Objective-C is 15 digits, I think that is a good clue about what is going on in your program.
I think that when you are doing this¨
[NSNumber numberWithDouble:[tempString doubleValue]]];
You are limiting the value of the NSNumber, because doubleValue is going to have a limit!

Formatting a number to show commas and/or dollar sign

I want to format my UILabel with commas or better with a dollar sign and commas (with no decimal).
Here is the code I am using:
IBOutlet UILabel *labelrev
float rev = (x + y)
labelrev.text = [[NSString alloc] initWithFormat:#%2.f",rev];
I get xxxxxxxxx as the output I want to get xxx,xxx,xxx or $xxx,xxx,xxx
How do I do that?
You should definitely use NSNumberFormatter for this. The basic steps are:
Allocate, initialize and configure your number formatter.
Use the formatter to return a formatted string from a number. (It takes an NSNumber, so you'll need to convert your double or whatever primitive you have to NSNumber.)
Clean up. (You know, memory management.)
This code sets up the number formatter. I've done everything that you want except the currency bit. You can look that up in the documentation.
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];
Next, you want to set up your number and return a formatted string. In your case, we wrap a double in an NSNumber. I do it inline, but you can break it up into two steps:
NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithFloat:rev];
Don't forget to clean up!
[formatter release];
A quick note about localization:
The NSLocale class provides some useful info about the user's locale. In the first step, notice how I used NSLocale to get a localized grouping separator:
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
(Some countries use a full-stop/period, while others use a comma.) I think there's a way to get a localized currency symbol as well, but I'm not one hundred percent sure, so check the documentation. (It depends upon what your trying to do.)
You will need to use a NSNumberFormatter which supports currency.
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLog(#"%#", [currencyFormatter stringFromNumber:[NSNumber numberWithInt:10395209]]);
[currencyFormatter release];
Prints: $10,395,209.00
[formatterCurrency setMaximumFractionDigits:0]
is only way to trancate decimal digits and decimal separator in a NSNumberFormatterCurrencyStyle formatter.
NSNumberFormatter *formatterCurrency;
formatterCurrency = [[NSNumberFormatter alloc] init];
formatterCurrency.numberStyle = NSNumberFormatterCurrencyStyle;
[formatterCurrency setMaximumFractionDigits:0];
[formatterCurrency stringFromNumber: #(12345.2324565)];
result
12,345 $

Objective-C: How to format string as $ Price

Is their a built-in way of formatting string as $ price, e.g. 12345.45 converted to $12,345.45?
Assuming you are using Cocoa (or just Foundation), you can use NSNumberFormatter and set its style to currency:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
... = [formatter stringFromNumber:number];
By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.
Assuming the price is held in a float, you probably want +localizedStringWithFormat:.
NSString *priceString = [NSString localizedStringWithFormat:#"$ %'.2f",price];
Hmmm... Apple says they follow the IEEE standard for printf, so it should accept the ' flag, but it doesn't work on Tiger. NSNumberFormatter it is.
You need to get rid of the ' character
So, just have this:
NSString *priceString = [NSString localizedStringWithFormat:#"$ %.2f", price];
NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];