iPhone NSNumberFormatter for less than 1 value - iphone

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.

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.

Divide int and return a float

I have a problem that I can not fix with a number, I'll explain.
At one point in my code I call a function that returns an int, then I divide it and have a float with two decimal places.
My Ex 69033792 Fuzion back, I want to have to divide by 1024 and 67415.81
I write
NSInteger mem_0 = [self printMemoryInfo:#"0"];
[self.mem1 setText:[NSString stringWithFormat:#"%.2f",(mem_0/1024f)]];
but I do not return the decimal part ... What's wrong?
thanks
myDouble = [[NSNumberFormatter alloc] init];
[myDouble setFormatterBehavior:NSNumberFormatterBehavior10_4];
[myDouble setNumberStyle:NSNumberFormatterDecimalStyle];
[myDouble setRoundingMode:NSNumberFormatterRoundHalfUp];
[myDouble setMinimumFractionDigits:0];
[myDouble setMaximumFractionDigits:2];
NSInteger mem_0 = [self printMemoryInfo:#"0"];
[self.mem1 setText:[myDouble stringFromNumber:[NSNumber numberWithDouble: mem_0/1024]]];
[myDouble release];
You should be getting the compile-time error "Invalid digit 'f' in decimal constant", because 1024f is not legal. You need to say it like this:
[self.mem1 setText:[NSString stringWithFormat:#"%.2f",(mem_0/1024.0f)]];
or you can just say 1024.0 without the f, because it will be passed to stringWithFormat: as a double anyway.

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

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.

What is wrong with this string format (different behavior on simulator and device)?

I have this block of code executed when pressing a number:
NSString *currentValue = [#"" stringByAppendingFormat:#"%.02f", [[[[[textField text] stringByReplacingOccurrencesOfString:#"." withString:#""] stringByReplacingOccurrencesOfString:#"," withString:#""] stringByReplacingOccurrencesOfString:#" " withString:#""] doubleValue]/100.0f];
//I am using this to obtain always a number with 2 decimals.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setMinimumFractionDigits:2];
[f setMaximumFractionDigits:2];
[f setGroupingSeparator:#" "];
NSNumber *currentNumberValue = [f numberFromString:currentValue];
NSLog(#"1: %#", currentValue);
NSLog(#"2: %#", [currentNumberValue stringValue]);
Now if I run this in the simulator and press 3 I get the following results:
1: 0.03
2: 0.03
If I run it on the device I have:
1: 0.03
2: 0
So basically on the device the formated number is 0.
What I have also noticed is that on the simulator I get '.' as a decimal separator and on the device I have ','.
And because of this it never gets further. Any number I press it still remains 0.
What seems to be the problem?
Your device is apparently set to a European (or wherever) locale that uses , as the decimal separator. Try adding this line after the line where you alloc and init your number formatter:
[f setDecimalSeparator:#"."];
Or use the setLocale method (or change the locale your device is set to).
Try it like this:
NSString *currentValue = [textField text];
float currentFloat = [currentValue floatValue];
NSLog(#"%.2f",currentFloat); //string representation of floatValue
NSLog(#"%#",currentValue); //string currentValue