Suppressing unnecessary zeros - ios

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).

Related

NSNumberFormatter for 2 Decimal Places

I have some amount that i want to Display in local Style.
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
numberFormatter.locale = [NSLocale currentLocale];
numberFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
numberFormatter.usesGroupingSeparator = YES;
NSString* amountText = [NSString stringWithFormat:#"ab %#€",[numberFormatter stringFromNumber:someDoubleNumber]];
Problem is that this is also displaying the currency and that is something that i don't want. Basically what i am looking for is displaying that decimal should be according to local Style with 2 numbers after decimal for example 0.00 or in germany 0,00 with my code i am achieveing this requirement but i am also getting the additionally the currency symbol which i don't want.
Anybody still looking for an answer i achieved it by
[numberFormatter setCurrencySymbol:#""];

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

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 setFormat error

Working on my first iOS app. I think that this code should work, but I get the following error. Maybe I am missing an import or something?
No visible #interface for 'NSNumberFormatter' declares the selector'setFormat'
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
[formatter setFormat:#"#0.00"];
You cann't call setFormat: for NSNumberFormatter.
Some sample code:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
NSLog(#"Formatted number string:%#",string);
numberStyle enum:
enum {
NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
};
reslut for each numberStyle:
[1243:403] Formatted number string:123456789
[1243:403] Formatted number string:123,456,789
[1243:403] Formatted number string:¥123,456,789.00
[1243:403] Formatted number string:-539,222,988%
[1243:403] Formatted number string:1.23456789E8
[1243:403] Formatted number string:one hundred twenty-three million four hundred fifty-six thousand seven hundred eighty-nine
You can't set the format as you provided here. Set the number format as given below
[formatter setNumberStyle:NSNumberFormatterSpellOutStyle];
//or other styles like NSNumberFormatterDecimalStyle,NSNumberFormatterPercentStyle
or you can create a custom number format as
[formatter setPositiveFormat:#"#0.00"];
A nice tutorial is given here
http://useyourloaf.com/blog/2012/06/14/using-number-formatters.html

NSNumberformatter add extra zero

I'm looking for a way to display "1" as "01", so basically everything below 10 should have a leading 0.
What would be the best way to do this?
I know I can just use a simple if structure to do this check, but this should be possible with NSNumberformatter right?
If you just want an NSString, you can simply do this:
NSString *myNumber = [NSString stringWithFormat:#"%02d", number];
The %02d is from C. %nd means there must be at least n characters in the string and if there are less, pad it with 0's. Here's an example:
NSString *example = [NSString stringWithFormat:#"%010d", number];
If the number variable only was two digits long, it would be prefixed by eight zeroes. If it was 9 digits long, it would be prefixed by a single zero.
If you want to use NSNumberFormatter, you could do this:
NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPaddingPosition:NSNumberFormatterPadBeforePrefix];
[numberFormatter setPaddingCharacter:#"0"];
[numberFormatter setMinimumIntegerDigits:10];
NSNumber *number = [NSNumber numberWithInt:numberVariableHere];
----UPDATE------
I think this solves your problem:
[_minutes addObject:[NSNumber numberWithInt:i]];
return [NSString stringWithFormat:#"%02d", [[_minutes objectAtIndex:row] intValue]];
FIXED for Swift 3
let x = 999.1243
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 1 // for float
formatter.maximumFractionDigits = 1 // for float
formatter.minimumIntegerDigits = 10 // digits do want before decimal
formatter.paddingPosition = .beforePrefix
formatter.paddingCharacter = "0"
let s = formatter.string(from: NSNumber(floatLiteral: x))!
OUTPUT
"0000000999.1"

Resources