Divide int and return a float - iphone

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.

Related

NSNumberFormatter's multiplier rounds down instead of showing fraction

I have configured an NSNumberFormatter to convert amounts that are stored as cents in an NSDictionary to euro's. Because they're stored as cents, I have set the formatter's multiplier to [NSNumber numberWithDouble:0.01]. However, when I try to display 304 euro cents as euro's I get € 3,00.
This leads me to believe that the multiplier is doing integer division instead of double division.
NSFormatter configuration
/**
Returns an NSNumberFormatter that can be used to display currency in euro's (as determined in The Netherlands).
*/
+ (NSNumberFormatter *)euroCurrencyFormatter
{
static NSNumberFormatter *numberFormatter = nil;
#synchronized(self) {
if (!numberFormatter) {
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setMultiplier:[NSNumber numberWithDouble:0.01]];
NSLocale *nlLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"nl_NL"];
[numberFormatter setLocale:nlLocale];
[nlLocale release];
}
}
return numberFormatter;
}
Calling the NSFormatter
cell.detailTextLabel.text = [[NSNumberFormatter euroCurrencyFormatter] stringFromNumber:[breakdown valueForKey:#"VatAmount"]]; // The VAT amount would be 304.
Result
€ 3,00
How can I stop errounous behaviour?
Try this code.
cell.detailTextLabel.text = [[NSNumberFormatter euroCurrencyFormatter] stringFromNumber:[NSNumber numberWithDouble:[[breakdown valueForKey:#"VatAmount"] doubleValue]]]; // The VAT amount would be 304.
As if you pass VAT as a integer you will get the number always in int format.
See the "Configuring Rounding Behavior" of the NSNumberFormatter reference.

Formatting float values

This is probably a stupid question but anyway.
I wan the number I set on my label to be formated nicely like this 20,000,000 .
How do I do this ?
For now I've set the number of decimal points to 0 so I just get the whole number without any places.
[NSString stringWithFormat:#"%.0f", slider.value];
you can use the following formatter:
-(void)setCurrencyFormat
{
NSNumberFormatter *CurrencyFormat = [[NSNumberFormatter alloc] init];
[CurrencyFormat setNumberStyle:NSNumberFormatterCurrencyStyle];
label.text= [CurrencyFormat stringFromNumber:[NSNumber numberWithDouble:billAmountInDouble]];
NSString *st1=[NSString stringWithFormat:#"%#",[CurrencyFormat stringFromNumber:[NSNumber numberWithDouble:individualTaxInDouble]]];
label.text=st1;
}
Check out the docs for NSNumberFormatter - you can do pretty much everything with that.

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.

UIKeyboardTypeDecimalPad - change comma to dot

I use this method to show keyboard with decimal separator
myTextField.keyboardType=UIKeyboardTypeDecimalPad;
How can I change comma to dot separator?
I have a Finnish locale. With comma, decimals doesn't work on my app.
-(IBAction)calculate {
float x = ([paino.text floatValue]) / ([pituus.text floatValue]) *10000;
label.text = [[NSString alloc] initWithFormat:#"%0.02f", x];
}
OK so you edit a text field using a numeric keyboard, which is dependent on the current locale, and thus get a text representation of a number, which is dependendt on the current locale, too. After editing has finished you read it and want to transform into a number.
To convert you would use NSNumberFormatter like this:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
You can setup the formatter as you will, setting locale (!), limits, formatting, decimal/grouping separator, number of decimal digits etc. Then you just use it:
float number = [nf numberFromString: field.text];
And that's all! Now you have the number even if the text includes comma, provided you let both: keyboard and formatter, to have the same format, same style - i.e. probably just let current locale be used all over the place.
EDIT
this is a currency formatter, that can convert between string and number for currencies:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle: NSNumberFormatterCurrencyStyle];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 2]
this is a percentage formatter with 4 decimal places:
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle: NSNumberFormatterPercentStyle];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 4];
both in the current locale.
As you see you can define the style, digits, rounding behaviour and much more, depending on numbers you are trying to enter. For more details (it is really a lot you can do with the NSNumberFormatter) you should read Apple docs, it would go beyond the scope of SO answer to describe it all.
In your case, provided that paino and pituus are also UITextFields:
-(IBAction)calculate {
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 2];
float npaino = [[nf numberFromString: paino.text] floatValue];
float npituus = [[nf numberFromString: pituus.text] floatValue];
float x = npaino] / npituus *10000;
label.text = [nf stringFromNumber: [NSNumber numberWithFloat: x]];
[nf release];
}
Now to avoid creating the formatter in each calculation you could make it an instance variable, since you need only one for those conversions.
Easyer that way:
[[yourField text] stringByReplacingOccurrencesOfString:#"," withString:#"."]
It will work in all ways and languages.
In your code, it will be:
-(IBAction)calculate {
float fPaino = [[paino.text stringByReplacingOccurrencesOfString:#"," withString:#"."] floatValue];
float x = fPaino / ([pituus.text floatValue]) *10000;
label.text = [[NSString alloc] initWithFormat:#"%0.02f", x];
}
Something else: are you sure to need an "alloc" for the result? As the label.text contains already its retain/release, you can simply make a [NSString stringWithFormat:#"%0.02f", x]