iphone NSString stringWithFormat and float - iphone

I have an input with UIKeyboardTypeDecimalPad and I need my user to input a float (with unlimited characters after a dot). After the input I filter the string with :
NSString *newValue = [NSString stringWithFormat:#"%.f",[textField.text floatValue]]
But that gives me a lot of unnecessary digits after a dot (for example for 2.25 it gives 2.249999).
All I need is to filter the input so it'll be a legal float (digits and not more than one dot).
How do I do that?

NSString *newValue = [NSString stringWithFormat:#"%0.1f", [textField.text floatValue]];
the number after the dot is the number of decimal places you want.
UPDATE:
You could use string manipulation to determine the number of decimal places the user typed in (don't forget to check for edge cases):
NSInteger numberOfDecimalPlaces = textString.length - [textString rangeOfString:#"."].location - 1;
and then if you want to create a new string with a new float to the same level of display precision you could use:
NSString *stringFormat = [NSString stringWithFormat:#"%%0.%if", numberOfDecimalPlaces];
NSString *newString = [NSString stringWithFormat:stringFormat, newFloat];

Not sure if this is what you want but try something like the following:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
// set to long number of decimals to accommodate whatever a user might enter
[nf setMaximumFractionDigits:20];
NSString *s = [nf stringFromNumber:
[NSNumber numberWithDouble:[userEnteredNumberString doubleValue]]
];
NSLog(#"final:%#",s);

Try using a double instead of float. I think the double removes all trailing zero's.

Related

Showing formatted digits in textField iphone application

I am taking data from XMl file, the distance in xml is like
<distance>13.472987570222 km</distance>
Now i want to show just two digits after . operator. i.e i want to show in textField like 13.47 km. i have saved this distance digits in NSString *distance;
Thanks
float theDistance = [distance floatValue];
NSString *roundedDistance = [NSString stringWithFormat:#"%.2f",theDistance];
That will round to 2dp. :)
You can use very powerful class NSNumberFormatter:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setPositiveFormat:#"##0.## km"];
[numberFormatter setNegativeFormat:#"##0.## km"];
NSNumber *number = [NSNumber numberWithDouble:[distance doubleValue]];
NSString *formattedString = [numberFormatter stringFromNumber:number];
For more info read here
Strikes me you should really be converting the xml string into a float or some other such appropriate type and then using a format specifier when displaying the value.

iPhone NSNumberFormatter for less than 1 value

I have a floating point value
i.e. 0.0467
Want have a string
05
how can get it? Excluding the decimal point (.).
More precisely, if I have a floating point number, I want to divide it to integral and decimal, preferably into two string parts.
By following this, you will get desired result.
float floatValue = 0.0467;
NSString *str = [NSString stringWithFormat:#"%.2f", floatValue];
str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:#""];
NSLog(#"%#", str); // Result will be: 05
fDecimal = 0.04567;
NSString * strDecimal = [NSString stringWithFormat:#"%0.2f", fDecimal];
NSString * strDecimalPart = [strDecimal substringWithRange:NSMakeRange(2, 2)];
The setting you are looking for is called fraction digits:
NSNumberFormatter* f = [[[NSNumberFormatter alloc] init] autorelease;
[f setMaximumFractionDigits:2];
Optionally you can use -[NSNumberFormatter setRoundingMode:] to specify how rounding should be done.

Custom floating decimal points

label.text = [NSString stringWithFormat:#"%.2f",final];
The above statement displays the float value available in the variable "final" with two digits after decimal point.
I want to display number of decimals in depending upon the number i have give to a integer variable like this
label.text = [NSString stringWithFormat:#"%.if",j,final]
Here j is integer variable. Whatever the number i have taken for j that many decimals it should display. I need proper syntax to display the above statement.
The IEEE printf spec that Apple follows states:
A field width, or precision, or both, may be indicated by an asterisk
( '*' ). In this case an argument of type int supplies the field width
or precision.
This means that
label.text = [NSString stringWithFormat:#"%.*f",j,final]
might work, but I have no platform available to test it right now.
NSNumberFormatter has the ability to do what you want. Any of the following methods can be set using a variable before you format your string.
- (void)setMinimumIntegerDigits:(NSUInteger)number
- (void)setMinimumFractionDigits:(NSUInteger)number
- (void)setMaximumIntegerDigits:(NSUInteger)number
- (void)setMaximumFractionDigits:(NSUInteger)number
Data Formatting Guide - Number Formatters
I don't know if there's a one-liner that will do what you want, but you can always do:
NSString* formatString = [NSString stringWithFormat: #"%%.%if", j];
label.text = [NSString stringWithFormat:formatString, final];
You can use NSNumberFormatter,
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setFormatterBehavior:NSNumberFormatterBehaviorDefault];
[nf setNumberStyle:NSNumberFormatterDecimalStyle];
[nf setMaximumFractionDigits:j]; // Set the number of decimal places here
label.text = [nf stringFromNumber:[NSNumber numberWithFloat:final]];
[nf release];

intValue is missing decimals

I have a price that I need to convert based on the selected currency.
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"currency.plist"];
NSDictionary *plistDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
int price = [price intValue];
int currencyValue = [[plistDictionary valueForKey:#"EUR"] intValue];
int convertedCurrency = (price / currencyValue);
price is an NSNumber and the valueForKey is also a number from a plist file I have setup with conversion rates.
The problem I am having, is that my price is missing the decimals. Everytime I get the intValue from the price it's just rounded up or down. The same issue exists for the exchange rate I get from the plist.
I have looked into NSNumberFormatter but it won't let me setFormat for the NSNumberFormatter. Any advice, please?
int is an integer type - by definition it does not have a decimal value. Instead try:
float fprice = [price floatValue];
float currencyValue = [[plistDictionary valueForKey:#"EUR"] floatValue];
float convertedCurrency = (fprice / currencyValue);
intValue returns an integer, which (by definition) is rounded to a number without decimals.
You could use doubleValue, which returns a double (which does have the fractional portion) or decimalValue which returns a NSDecimal object.
Take the price string and remove the period. After that convert the NSString to and int, which means you end up with 4235 pennies (or 42 dollars and 35 cents). (Also, make sure that the price string you're getting has two decimal places! Some people are lazy, and output "3.3" for "$3.30".)
NSString *removePeriod = [price stringByReplacingOccurrencesOfString:#"." withString:#""];
int convertedPrice = [removePeriod intValue];
float exchangeRate;
Then get the exchange rates depending on which currency has been selected and use the following code:
int convertedCurrency = round((double)convertedPrice / exchangeRate);
addCurrency = [NSString stringWithFormat: #"%0d.%02d", (convertedCurrency / 100), (convertedCurrency % 100)];
addCurrency is your final price.
To deal with the exact number of deciamlas and if all your currencies have 2 decimal places (e.g not JPY) make all numbers the number of cents
e.g. store 43.35 EUR as 4235.
Then you can use in arithmetic and then just deal with formatting using value/100.0 and NSNumberFormatter

Decimal point adjustment for string in iPhone

I want to display a number in decimal format only if the number is not an integer. Like if the number is float it must be displayed with one decimal point. But if the number is an integer it must be displayed without a decimal point like its shown in the following link(second part of the code)
http://www.csharp-examples.net/string-format-double/
I am using a string like
NSString *temp =[NSString stringWithFormat:#"0.1f" , 10];
this temp is 10.0 I want it to be 10 but if I am doing as follows
NSString *temp =[NSString stringWithFormat:#"0.1f" , 10.9];
then it must be like 10.9
How to resolve this in iPhone.
You could check the value of the string against a cast, then format the string accordingly:
float x = 42.1; // whatever
long x_int = x;
bool is_integer = x_int == x;
NSString* temp = nil;
if (is_integer)
{
temp = [NSString stringWithFormat:#"%d", x_int];
}
else
{
temp = [NSString stringWithFormat:#"%0.1f", x];
}
I got the solution,
NSString *temp =[NSString stringWithFormat:#"%g" , 10.9];