Format NSDecimalNumber to currency by country code without loss of precision - ios

So right now I have the following code:
- (NSString*)convertToLocalCurrencyFormat:(NSDecimalNumber*)result {
NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = self.comparisonCurrency;
formatter.usesSignificantDigits = YES;
return [formatter stringFromNumber:result];
}
When I pass in an NSDecimalNumber* containing 678071967196719797153475347466.94627863, it gets formatted to ¥678,072,000,000,000,000,000,000,000,000 (with the currencyCode set to JPY). If I leave out the formatter.usesSignificantDigits = YES line, then it gets formatted to ¥678,071,967,196,719,797,153,475,347,467, closer, but still dropping the decimal and following values.
However, when I pass in 6780.0416000000012517376, it's formatted correctly to ¥6,780.04 with the significant digits line. It gets formatted to ¥6,780 without the significant digits line.
I know that NSNumberFormatter can take in any NSNumber as a parameter, but can only deal with values as precise as doubles, leaving NSDecimalNumber with no errors and incorrect results.
How can I format NSDecimalNumbers with currency codes without loss of precision?
Thanks

Try setting the minimum fraction digits instead:
formatter.minimumFractionDigits = 2;
HTH

Related

How to determine if locale currency has a decimal point

Is there anyway in objective-c to determine if a currency uses a decimal point (regardless of declared NSNumber type)?
I have multiple locales and I use NSNumberFormatter (based on locale) to set string currency string style, however before-hand I would like to know if the selected locale currency uses a decimal point.
[_cf setLocale:
[NSLocale localeWithLocaleIndentifier:[NSString stringWithFormat:#"%#",locale]]]];
[cf setNumberStyle:NSNUmberFormatterCurrencyStyle];
NSString *value = [cf stringFromNumber:price];
return value;
After creating the NSNumberFormatter with currency style, ask the formatter how many fraction digits it has.
NSInteger maxFractionDigits = cf.maximumFractionDigits;
if (maxFractionDigits == 0) {
// this currency is an integer, not a decimal
}
One example where this is true is the Japanese Yen (¥).

Float value from Decimal Pad in swift iOS

I have UITextField with Decimal Pad and i want to convert it's value to float.
var myValue: Float = NSString(string: myTextField.text).floatValue
On my emulator i have no problems: in Decimal Pad i see numbers and "." so i can enter values like 123.45, but on device i have a problem because on decimal pad i see numbers and ",". So after adding "123,45" to myTextField i see that
myValue = 123
I know that i can change "." to "," in setting but i am really not sure about my app users.
So my problem is - how can i get float value from decimal pad not only with "." using Swift?
I see two kind of solutions:
1) how can i config decimal pad to show "." instead of "," on any device?
2) how can i convert to float strings with "," delimiter?
I have this snippet only in ObjC, but the answer is that you need to use an NSNumberFormatter, the problem is due to a difference in how locale is managed from the input to the inner float representation.
numberformatter = [[NSNumberFormatter alloc] init];
[numberformatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberformatter setMaximumFractionDigits:2];
[numberformatter setMinimumFractionDigits:0];
[numberformatter setLocale:[NSLocale currentLocale]];
Here more hints on how to use number formatters

NSDecimalNumber rounding

I would to round a decimal number like this :
4363,65 ----> 4364
I have tried this :
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString#"4363,65"];
NSDecimalNumberHandler *behav = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain scale:NSDecimalNoScale
raiseOnExactness:YES
raiseOnOverflow:YES
raiseOnUnderflow:YES
raiseOnDivideByZero:YES];
NSDecimalNumber *roundedDecimal = [decimalNumber decimalNumberByRoundingAccordingToBehavior:behav];
I don't have the expected result.How i can round it ?
I see 2 problems in your code. The first is the creation of the number. You are using , as a decimal separator. If your locale is not configured to use , for decimals, your number will be parsed as 4363. This is what probably happens.
The second problem is the value for the scale parameter. It takes the number of decimal digits but you are using a constant NSDecimalNoScale which is actually equal to SHRT_MAX. That's not what you want.
//make sure you use the correct format depending on your locale
NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:#"4363.65"];
NSDecimalNumberHandler *behav = [[NSDecimalNumberHandler alloc] initWithRoundingMode:NSRoundPlain
scale:0
raiseOnExactness:YES
raiseOnOverflow:YES
raiseOnUnderflow:YES
raiseOnDivideByZero:YES];
This is the easiest way:
float f = 4363,65;
int rounded = (f + 0.5);

Using NSNumberFormatter to generate number with trailing zeros after decimal

In Swift, how would you create an NSNumberFormatter that would preserve trailing zeros after a decimal (12.000) while also generating a number appropriate for the current locale?
My current code and example output:
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.locale = NSLocale.currentLocale()
formatter.maximumFractionDigits = 10
var doubleNumString = "12.0"
println(formatter.numberFromString(doubleNumString)) //in English it prints 12, want it to print 12.0
var doubleNumString = "12.000"
println(formatter.numberFromString(doubleNumString)) //prints 12, want it to print 12.000
var doubleNumString = "12.125"
println(formatter.numberFromString(doubleNumString)) //prints 12.125 as expected
var doubleNumString = "1234"
println(formatter.numberFromString(doubleNumString)) //prints 1,234 as expected
I've already coded it such that if the string ends in a decimal ("12.") then it won't use this formatter to generate the number and will instead just display the number then the decimal (but I will need to improve that because some languages read right to left).
One solution would be to check if the string contains a period and if so, check if all digits that follow it are 0, and if so then don't run it through the number formatter and instead run only the int value through the formatter then append/prepend the decimal followed by the appropriate number of 0's.
Is there a better/cleaner solution?
As mentioned by Martin R, you can set the minimumFractionDigits and maximumFractionDigits to the same number which will enforce that many fraction digits always be displayed. To know how many to display you need to take a substring after the decimal to the end and count its elements. To know whether or not all of the fraction digits are 0's, I created a helper method that converts that substring to a number and if it equals 0 then you know they were all 0's.
Unfortunately you need to convert the string to a localized number using a couple different NSNumberFormatters based on the original string number. So if it does contain a decimal and everything after it is a 0 then you need to create a different formatter, convert the string to a number, then convert that number to a string in order to display it respecting the user's locale. Otherwise you can just use your original number formatter.
This function takes care of your requirement. pass same for & from locale (e.g. en_US)
+ (NSString*) stringForString:(NSString*) string forLocale:(NSString*) toLocaleCode fromLocal:(NSString*) fromLocaleCode {
NSLocale *fromLocale = [[NSLocale alloc] initWithLocaleIdentifier:fromLocaleCode];
NSNumberFormatter *sourceFormatter = [[NSNumberFormatter alloc] init];
[sourceFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[sourceFormatter setUsesGroupingSeparator:NO];
[sourceFormatter setLocale:fromLocale];
NSNumber *localizedNumber = [sourceFormatter numberFromString:string];
if (!localizedNumber) {
return string;
}
NSLocale *toLocale = [[NSLocale alloc] initWithLocaleIdentifier:toLocaleCode];
NSNumberFormatter *destinationFormatter = [[NSNumberFormatter alloc] init];
[destinationFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[destinationFormatter setUsesGroupingSeparator:NO];
[destinationFormatter setLocale:toLocale];
NSString *localizedString = [destinationFormatter stringFromNumber:localizedNumber];
//add the zeros which were dropped because of the sourceDecimalString number conversion e.g. 0.20 is converted to 0.2
if (localizedString.length < string.length) {
NSRange rangeOfDecimal = [string rangeOfString:sourceFormatter.decimalSeparator];
if (rangeOfDecimal.location != NSNotFound) {
NSString* sourceDecimalString = [string substringFromIndex:rangeOfDecimal.location];
rangeOfDecimal = [localizedString rangeOfString:destinationFormatter.decimalSeparator];
if (rangeOfDecimal.location != NSNotFound) {
NSString* destinationDecimalString = [localizedString substringFromIndex:rangeOfDecimal.location];
if (destinationDecimalString.length < sourceDecimalString.length) {
int difference = sourceDecimalString.length - destinationDecimalString.length;
int toalDecimalDigits = (destinationDecimalString.length - 1) + difference; //-1 to remove '.'
destinationFormatter.minimumFractionDigits = toalDecimalDigits;
destinationFormatter.maximumFractionDigits = toalDecimalDigits;
localizedString = [destinationFormatter stringFromNumber:localizedNumber];
}
}
else{//this indicates no decimal separator in the return string
int toalDecimalDigits = (sourceDecimalString.length - 1); //-1 to remove '.'
destinationFormatter.minimumFractionDigits = toalDecimalDigits;
destinationFormatter.maximumFractionDigits = toalDecimalDigits;
localizedString = [destinationFormatter stringFromNumber:localizedNumber];
}
}
}
return localizedString;
}

iOS - %G float can only handle six numbers

Why does the %g format for strings only handle six numbers in a float and after that it turns into scientific notation? Is there any other way of displaying a float with something similar to the %g format but allows more than six numbers?
EDIT: I have figured out %g with precision i.e turning %g into %.Xg where x is the specified number of significant digits. But it doesnt help me in this situation:
-(IBAction)numberPressed:(id)sender {
if (decimalChecker == 1) {
currentDecimal = currentDecimal*10+ (float)[sender tag];
decimaledNumberString = [[NSString alloc] initWithFormat:#"%.17g.%.17g", currentNumber, currentDecimal];
calculatorScreen.text = decimaledNumberString;
currentDecimaledNumber = [decimaledNumberString floatValue];
NSLog(#"regular");
} else {
currentNumber = currentNumber*10+ (float)[sender tag];
calculatorScreen.text = [[NSString alloc] initWithFormat:#"%.17g", currentNumber];
NSLog(#"regular");
}
}
If I press "5" eight times instead of 55555555, I get 55551782 or something similar. How can I fix it to where I get the desired eight fives instead of the crazy number?
Insert a period and a numeral to specify the maximum number of significant digits you would like displayed, such as %.17g for 17 significant digits. As you discovered, the default is six.
According to http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Strings/Articles/FormatStrings.html#//apple_ref/doc/uid/20000943, iOS string formatting uses the same placeholders as C's printf(), which specifies g/G as representing FP values with exponential notation for very large/small values while f only uses non-exponential representation.
http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders

Resources