Decimal point adjustment for string in iPhone - 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];

Related

iphone NSString stringWithFormat and float

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.

Unexpected result from "stringWithFormat:"

What would be the expected result from the following Objective C code?
int intValue = 1;
NSString *string = [NSString stringWithFormat:#"%+02d", intValue];
I thought the value of string would be "+01", it turns out to be "+1". Somehow "0" in format string "+01" is ignored. Change code to:
int intValue = 1;
NSString *string = [NSString stringWithFormat:#"%02d", intValue];
the value of string is now "01". It does generate the leading "0". However, if intValue is negative, as in:
int intValue = -1;
NSString *string = [NSString stringWithFormat:#"%02d", intValue];
the value of string becomes "-1", not "-01".
Did I miss anything? Or is this a known issue? What would be the recommended workaround?
Thanks in advance.
#Mark Byers is correct in his comment. Specifying '0' pads the significant digits with '0' with respect to the sign '+/-'. Instead of '0' use dot '.' which pads the significant digits with '0' irrespective of the sign.
[... stringWithFormat:#"%+.2d", 1]; // Result is #"+01"
[... stringWithFormat:#"%.2d", -1]; // Result is #"-01"
NSString *string = [NSString stringWithFormat:#"+0%d", intValue];
NSString *string = [NSString stringWithFormat:#"-0%d", intValue];

Convert string fraction to decimal

I have a plist file that I am reading out a measurement, but some of the measurements are fractions such as 6 3/8". I formatted them that way because it's easier to find that on a tape measure than it is to find 6.375". My problem is now I want to do a conversion to metric on the fly and it isn't reading in the fraction part of the number. My current code is this.
cutoutLabel.text = [NSString stringWithFormat:#"%.2f mm. %#", [[[sizeDict valueForKey:Sub_Size] objectForKey:#"Cutout Dimensions"]floatValue] * 25.4, [temp objectAtIndex:2]];
Thanks.
That's what I ended up doing.
NSArray *temp = [[[sizeDict valueForKey:Sub_Size] objectForKey:#"Cutout Dimensions"] componentsSeparatedByString:#" "];
if ([temp count] > 2) {
NSArray *fraction = [[temp objectAtIndex:1]componentsSeparatedByString:#"/"];
convertedFraction = [[fraction objectAtIndex:0]floatValue]/[[fraction objectAtIndex:1]floatValue];
}
You can get the numerator and denominator as follows:
NSRange slashPos = [fraction.text rangeOfString:#"/"];
NSString * numerator = [fraction.text substringToIndex:slashPos.location];
NSString * denominator = [fraction.text substringFromIndex:slashPos.location+1];
You should take more care than this,
check that your range is of length 1 and make sure that the string has characters after the "/" character. But if you know you are feeding this code a fraction string it should work in your case
The idea is in place, but you will also need to apply the same logic first to separate the whole number from you fraction. Apply the same logic, searching for a #" " and then find the numerator and denominator
Building on Ian's answer and trying to be a little more complete (since his example was for a whole number and fractional part with an inch character (6 3/8"), I suggest the following method (it also works if there are spaces before the whole number:
// Convert a string consisting of a whole and fractional value into a decimal number
-(float) getFloatValueFromString: (NSString *) stringValue {
// The input string value has a format similar to 2 1/4". Need to remove the inch (") character and
// everything after it.
NSRange found = [stringValue rangeOfString: #"\""]; // look for the occurrence of the " character
if (found.location != NSNotFound) {
// There is a " character. Get the substring up to the "\"" character
stringValue = [stringValue substringToIndex: found.location];
}
// Now the input format looks something like 2 1/4. Need to convert this to a float value
NSArray *temp = [stringValue componentsSeparatedByString:#" "];
float convertedFraction = 0;
float wholeNumber = 0;
for (int i=0; i<[temp count]; i++) {
if ([[temp objectAtIndex:i] isEqualToString:#""]) {
continue;
}
NSArray *fraction = [[temp objectAtIndex:i]componentsSeparatedByString:#"/"];
if ([fraction count] > 1) {
convertedFraction = [[fraction objectAtIndex:0]floatValue]/[[fraction objectAtIndex:1]floatValue];
}
else if ([fraction count] == 1) {
wholeNumber = [[fraction objectAtIndex:0] floatValue];
}
}
convertedFraction += wholeNumber;
return convertedFraction;
}

String to double

I hope you can help me out with this 'small' problem. I want to convert a string to a double/float.
NSString *stringValue = #"1235";
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue doubleValue]/(double)100.00];
I was hoping this to set the priceLabel to 12,35 but I get some weird long string meaning nothing to me.
I have tried:
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue intValue]/(double)100.00];
priceLabel.text = [NSString stringWithFormat:#"%d",[stringValue doubleValue]/100];
but all without success.
This is how to convert an NSString to a double
double myDouble = [myString doubleValue];
You have to use %f to show float/double value.
then %.2f means 2digits after dot
NSString *stringValue = #"1235";
NSString *str = [NSString stringWithFormat:#"%.2f",[stringValue doubleValue]/(double)100.00];
NSLog(#"str : %# \n\n",s);
priceLabel.text = str;
OUTPUT:
str : 12.35
I think you have the wrong format string. Where you have:
[NSString stringWithFormat:#"%d", ...];
You should really have:
[NSString stringWithFormat:#"%f", ...];
%d is used for integer values. But you're trying to display a floating point number (%f).

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