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];
Related
I am formatting floating point numbers and right now I have the %0.2f formatter, but I'd like to omit the .00 if the floating point number is an even integer.
Of course I can think of string replacing the .00, but that's crude.
I found that the description of NSNumber also does something similar:
NSNumber *number = [NSNumber numberWithFloat:_paragraphSpacing];
[retString appendFormat:#"margin-bottom:%#px;", number];
This this does hover not limit the post comma digits. if the number is 1234.56789 then the description will output that.
So my question is, is there a just as simple way - possibly without having to create an NSNumber object - to achieve this result?
Since floating-point numbers aren't exact, there's no guarantee that your number will actually be an integer. You can, however, check if it's within a reasonably small distance from an integer value. And of course you don't need an NSNumber for this. (Generally speaking, NSNumber is not used for formatting, its purpose is representing a primitive C type, either integral or floating-point types, using an Objective-C object.)
#include <math.h>
- (NSString *)stringFromFloat:(float)f
{
const float eps = 1.0e-6;
if (abs(round(f) - f) < eps) {
// assume an integer
return [NSString stringWithFormat:#"margin-bottom: %.0fpx", round(f)];
} else {
// assume a real number
return [NSString stringWithFormat:#"margin-bottom: %.2fpx", f];
}
}
Use a formatter:
NSNumberFormatter* formatter= [NSNumberFormatter new];
formatter.numberStyle= NSNumberFormatterDecimalStyle;
formatter.maximumFractionDigits=2;
NSNumber *number = [NSNumber numberWithFloat:_paragraphSpacing];
[retString appendFormat:#"margin-bottom:%#;", [formatter stringFromNumber: number]];
You can use an NSNumberFormatter for this:
static NSNumberFormatter *numberFormatter = nil;
if (numberFormatter == nil) {
numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.minimumFractionDigits = 0;
numberFormatter.maximumFractionDigits = 2;
numberFormatter.usesGroupingSeparator = NO;
}
NSString *formattedNumberString = [numberFormatter
stringForNumber:[NSNumber numberWithDouble: _paragraphSpacing]];
You can use C function modff to get the fraction part and test it:
float fractionPart = 0.;
modff(_paragraphSpacing, &fractionPart);
if( fabsf(fractionPart) < 0.01 ) {
// format as integer
[retString appendFormat:#"margin-bottom:%d", (int)_paragraphSpacing];
} else {
// format as float
[retString appendFormat:#"margin-bottom:%0.2f", _paragraphSpacing];
}
I would like to make it so one of my UILabels only shows a maximum of 3 digits. So, if the associated value is 3.224789, I'd like to see 3.22. If the value is 12.563, I'd like to see 12.5 and if the value is 298.38912 then I'd like to see 298. I've been trying to use NSNumberFormatter to accomplish this, but when I set the maximum significant digits to 3 it always has 3 digits after the decimal place. Here's the code:
NSNumberFormatter *distanceFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[distanceFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[distanceFormatter setAlwaysShowsDecimalSeparator:NO];
[distanceFormatter setMaximumSignificantDigits:3];
I always thought 'significant digits' meant all the digits, before and after the decimal point. Anyway, is there a way of accomplishing this using NSNumberFormatter?
Thanks!
I believe that
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesSignificantDigits = YES;
formatter.maximumSignificantDigits = 3;
will do exactly what you want, i.e. it will always show exactly 3 digits, be it 2 before the decimal and 1 after or 1 before the decimal and 2 after.
Perhaps you also have to set (not sure though):
[distanceFormatter setUsesSignificantDigits: YES];
But in your case it's probably much easier to just use the standard string formatting:
CGFloat yourNumber = ...;
NSString* stringValue = [NSString stringWithFormat: #"%.3f", yourNumber];
(note: this will round the last digit)
Heres a small function I wrote:
int nDigits(double n)
{
n = fabs(n);
int nDigits = 0;
while (n > 1) {
n /= 10;
nDigits++;
}
return nDigits;
}
NSString *formatNumber(NSNumber *number, int sigFigures)
{
double num = [number doubleValue];
int numDigits = nDigits(num);
NSString *format = [NSString stringWithFormat:#"%%%i.%ilf", sigFigures -= numDigits, sigFigures];
return [NSString stringWithFormat:format, num];
}
In my tests, this worked fine.
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.
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.
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]