I have one double value. I have to display a double value separated by a commas in a UILabel. But instead of commas i got dot. Here is my code.
double totalCost = [abcCost doubleValue] + [defCost doubleValue];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
numberFormatter.locale = [NSLocale currentLocale];// this ensures the right separator behaviour
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.usesGroupingSeparator = YES;
NSNumber *totalCostNum = [NSNumber numberWithDouble:totalCost];
NSString *totCostStr = [numberFormatter stringFromNumber:totalCostNum];
NSLog(#"%#", totCostStr);//123,345.46 prints
costLabel.text = [NSString stringWithFormat:#"$ %#", totCostStr];
while display that value in UILabel it shows 123.345.46. I want to display the value in this format 123,345.46.
Thanks in advance.
The above code is correct. I had done a small mistake. UILabel height is small, that's why it seems to be a dot. When i increased the height it displays comma.
Related
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.
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
I have a UILabel that shows the outside temperature, the problem is, sometimes it shows it as a XX.XXº format instead of the normal XXº or XXXº format used to show temperature, is there anyway to force the label to only show the temperature without the decimals or at least force it to only be able to use 2 characters?
You can use this to eliminate the decimals:
NSString* numberString = [NSString stringWithFormat:#"%.0f", d]; // 0 means no decimals
Otherwise I believe this will work to limit the number of chars to 2:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesSignificantDigits = YES;
formatter.maximumSignificantDigits = 2;
I have not really used NSNumberFormatter very much though.
NSString *temp = [galleryEntryTree objectForKey:#"description"];
if ([temp length] > 500) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 500}];
temp = [temp substringWithRange:range];
temp = [temp stringByAppendingString:#" …"];
}
coverView.label2.text = temp;
You may also use substring method
NSString *newformat = [NSString stringWithFormat:#"%#",[temperature substringWithRange:NSMakeRange(0,2)]];
In this case temperature is a string that you set for your label and you are only retrieving the 1st 2 digits only
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"
I am developing an application in which I wish to handle different currency formats, depending on the current locale. Using a NSNumberFormatter I can correctly translate a number into string and back without problems.
But, if I put the string value into a UITextField and later get it back, I won't be able to convert the string back into a number and I will get a nil value instead.
Here is a sample code to explain the problem:
NSNumberFormatter *nf = [Utils currencyFormatter];
NSNumber *n = [NSNumber numberWithInt:10000];
NSString *s = [nf stringFromNumber:n];
NSLog(#"String value = %#", s);
UITextField *t = [[UITextField alloc] init];
// I put the string into the text field ...
t.text = s;
// ... and later I get the value back
s = t.text;
NSLog(#"Text field text = %#", s);
n = [nf numberFromString:s];
NSLog(#"Number value = %d", [n intValue]);
where the currencyFormatter method is defined this way:
+ (NSNumberFormatter *)currencyFormatter
{
static NSNumberFormatter *currencyFormatter;
if (!currencyFormatter) {
currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormatter setLocale:[NSLocale currentLocale]];
if ([currencyFormatter generatesDecimalNumbers] || [[currencyFormatter roundingIncrement] floatValue] < 1) {
[currencyFormatter setGeneratesDecimalNumbers:YES];
[currencyFormatter setRoundingIncrement:[NSNumber numberWithFloat:0.01]];
}
}
return currencyFormatter;
}
(The inner if is used to force the formatter to always round to the smallest decimal digit, eg. even for CHF values).
What I get in the Console is this:
2012-03-29 00:35:38.490 myMutuo2[45396:fb03] String value = € 10.000,00
2012-03-29 00:35:38.494 myMutuo2[45396:fb03] Text field text = € 10.000,00
2012-03-29 00:35:38.497 myMutuo2[45396:fb03] Number value = 0
The strange part is that the spacing character between € and 1 in the first line is represented in the console through a mid-air dot, while in the second line this dot disappears. I believe this is an encoding-related problem.
Can anyone help me solve this problem?
Thank you!
Edit
I changed my test code to this:
NSNumberFormatter *nf = [Utils currencyFormatter];
NSNumber *n = [NSNumber numberWithInt:10000];
NSString *s = [nf stringFromNumber:n];
NSLog(#"String value = %# (space code is %d)", s, [s characterAtIndex:1]);
UITextField *t = [[UITextField alloc] init];
t.text = s;
s = t.text;
NSLog(#"Text field text = %# (space code is %d)", s, [s characterAtIndex:1]);
n = [nf numberFromString:s];
NSLog(#"Number value = %d", [n intValue]);
to discover this:
2012-03-29 02:29:43.402 myMutuo2[45993:fb03] String value = € 10.000,00 (space code is 160)
2012-03-29 02:29:43.405 myMutuo2[45993:fb03] Text field text = € 10.000,00 (space code is 32)
2012-03-29 02:29:43.409 myMutuo2[45993:fb03] Number value = 0
The NSNumberFormatter writes down the space as a non-breaking space (ASCII char 160), and then the UITextField re-encodes that space as a simple space (ASCII char 32). Any known workaround for this behaviour? Perhaps I could just make a replacement of the space with a non-breaking space but ... will it work for all the locales?
A possible workaround: You could try to parse only the number values (and punctiation) via a regex pattern and create you currency value based on that number. If you do it in that way it is perhaps even more forgivable for the user, if he typed another currency symbol or other symbols that shouldnt be there...
I was able to solve this problem only extending the UITextField through a custom class. In this new class I put a new #property of type NSString in which I store the "computed" string value for the text field. This string will never be modified and will preserve the original encoding of the content of the text field.
When you need to work again on the original untouched content of the text field you have to refer to this new property instead of referring to the text property.
Using a separate string container is the only way to avoid these strange encoding changes.