Format number as percent - objective-c

I have written this code and I want to format the number z as percent.
float l = ([textField2.text floatValue]);
float g = ([textField1.text floatValue]);
float x = l/1.23;
float y = x-g;
float z = y/l;
label.text = [[NSString alloc] initWithFormat:#"%2.2f \%",z];

Make your code as follows.
label.text = [[NSString alloc] initWithFormat:#"%2.2f %%",(z*100)];

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
[numberFormatter setMinimumFractionDigits:2]; //optional
....
NSNumber *number = [NSNumber numberWithFloat:0.435];
NSLog(#"%#", [numberFormatter stringFromNumber:number] );
43,50 %

You need to use %% in order to print a percent sign in a format string.

Related

Objective C remove trailing zeros after decimal place

I am trying to get number in 2 decimal places with trailing zeros.
e.g
11.633-> 11.63
11.630-> 11.63
11.60-> 11.6
11-> 11
12928.98-> 12928.98
for this I written below line
#define kFloatFormat2(x) [NSString stringWithFormat:#"%g", [[NSString stringWithFormat:#"%.2f", x] floatValue]]
NSNumber *number1 = [NSNumber numberWithDouble:12928.98];
NSLog(#"number1:%#", number1);
NSString *string1 = kFloatFormat2([number1 floatValue]);
NSLog(#"string1:%#", string1);
the output of above prints
number1:12928.98
string1:12929
Why it prints 12929 value for string1
I want it as 12928.98.
Have you tried using a number formatter?
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setUsesGroupingSeparator:NO];
[formatter setMaximumFractionDigits:fractionDigits];
[formatter setMinimumFractionDigits:fractionDigits];
Now do something like
NSNumber *x = #23423;
NSString *value = [formatter stringFromNumber:x];
NSLog(#"number = %#, value);
You macro makes no sense. Just make it:
#define kFloatFormat2(x) [NSString stringWithFormat:#"%.2f", [x floatValue]]
where x is an NSNumber. And then you would call it like this:
NSString *string1 = kFloatFormat2(number1);
Or just do this:
double x = 12928.98;
NSLog(#"number = %.2f", x);

Rounding float number upto two decimal places

I am trying to round a floating value upto two decimal places. I am using objective-c
e.g 1.47567 should be like this , 1.47 .. Please help
Thnx .
float num = 1.47567;
num *= 100;
if(num >= 0) num += 0.5; else num -= 0.5;
long round = num;
num = round;
num /= 100;
NSLog(#"%.2f",num);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSString *formattedNumber = [formatter stringFromNumber:#(self.speed)];
double value = 1.47567;
double roundedValue = round(value * 100.0) / 100.0;
Of course you can use a named constant in place of 100.0. This is just a demo.
Do this
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSString *formattedNumber = [formatter stringFromNumber:#(self.speed)];
float numTwoDecimalDigits = atof([formattedNumber UTF8String]);
NSLog(#"%.2f", 1.47567);
would round to two decimal places. If you want to "cut", there are different options. For example:
NSLog(#"%.2f", floor(1.47567 * 100) / 100);

NSNumberFormatter to stop shortening numbers

EDIT: Fixed, here is how i did it for furture reference:
NSNumber *inputNumber = [[NSNumber alloc ]initWithDouble:convertValue];
NSNumber *resultNumber = [[NSNumber alloc]initWithDouble:result];
NSNumberFormatter *formatterResult = [[NSNumberFormatter alloc] init];
formatterResult.numberStyle = NSNumberFormatterDecimalStyle;
NSNumberFormatter *formatterInput = [[NSNumberFormatter alloc] init];
formatterInput.numberStyle = NSNumberFormatterDecimalStyle;
[formatterResult setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterResult setMaximumFractionDigits:6];
[formatterInput setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterInput setMaximumFractionDigits:6];
//These four lines are the one fixing the issue.
NSString *formattedResultString = [formatterResult stringFromNumber:(NSNumber*)resultNumber];
NSString *formattedInputString = [formatterInput stringFromNumber:(NSNumber*)inputNumber];
NSString *formelString = [[NSString alloc]initWithFormat:
#" %# %# =", formattedInputString, convertFromName];
formelLabel.text = formelString;
NSString *resultString = [[NSString alloc]initWithFormat:
#" %# %#",formattedResultString, convertToName];
resultLabel.text = resultString;
----------ORIGINAL QUESTION------------
So I have a problem with NSNumberFormatter shortening numbers too much, and also not displaying decimals when the main number is over 8 digits.
Problem described in following picture:
<- Working, but shortening to three decimals. (And rounding up, which is done mathematically correct)
And then the problems: (Right-most picture is correct)
As you can see, the bottom image just ignores the decimals completely. What code do I need to add/change for this to work properly?
Here is the relevant code:
[super viewDidLoad];
_convertFrom = #[#"MTPA", #"MMcf/day",
#"Mill.Sm3/day", #"MMBTU/day", #"Boe/day",#"ton LNG/day", #"GJ/day"];
_convertTo = #[#"MTPA", #"MMcf/day",
#"Mill.Sm3/day", #"MMBTU/day", #"Boe/day", #"ton LNG/day", #"GJ/day"];
_convertRates = #[ #1.0f, #133.3333333f, #3.775579545f,
#137333.3333f, #23747.68013, #1716.17252, #147247.6022];
//some place down in the code:
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
[self updateConversionLabel];
}
- (void)updateConversionLabel
{
float convertFrom = [[_convertRates objectAtIndex:[picker selectedRowInComponent:0]] floatValue];
float convertTo = [[_convertRates objectAtIndex:[picker selectedRowInComponent:1]] floatValue];
NSNumberFormatter *fmt = [NSNumberFormatter new];
float input = [fmt numberFromString:inputText.text].floatValue;
float to = convertTo;
float from = convertFrom;
float convertValue = input;
float relative = to / from;
float result = relative * convertValue;
NSString *convertFromName = [_convertFrom objectAtIndex:[picker selectedRowInComponent:0]];
NSString *convertToName = [_convertFrom objectAtIndex:[picker selectedRowInComponent:1]];
NSNumber *inputNumber = [[NSNumber alloc ]initWithFloat:convertValue];
NSNumber *resultNumber = [[NSNumber alloc]initWithFloat:result];
NSNumberFormatter *formatterResult = [[NSNumberFormatter alloc] init];
formatterResult.numberStyle = NSNumberFormatterDecimalStyle;
NSNumberFormatter *formatterInput = [[NSNumberFormatter alloc] init];
formatterInput.numberStyle = NSNumberFormatterDecimalStyle;
NSString *formattedResultString = [formatterResult stringFromNumber:(NSNumber*)resultNumber];
NSString *formattedInputString = [formatterInput stringFromNumber:(NSNumber*)inputNumber];
NSString *formelString = [[NSString alloc]initWithFormat:
#" %# %# =", formattedInputString, convertFromName];
formelLabel.text = formelString;
NSString *resultString = [[NSString alloc]initWithFormat:
#" %# %#",formattedResultString, convertToName];
resultLabel.text = resultString;
}
I'd assume the problem/fix is in this code.
EDIT: Fixed, here is how I did it for future reference:
NSNumber *inputNumber = [[NSNumber alloc ]initWithDouble:convertValue];
NSNumber *resultNumber = [[NSNumber alloc]initWithDouble:result];
NSNumberFormatter *formatterResult = [[NSNumberFormatter alloc] init];
formatterResult.numberStyle = NSNumberFormatterDecimalStyle;
NSNumberFormatter *formatterInput = [[NSNumberFormatter alloc] init];
formatterInput.numberStyle = NSNumberFormatterDecimalStyle;
[formatterResult setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterResult setMaximumFractionDigits:6];
[formatterInput setNumberStyle:NSNumberFormatterDecimalStyle];
[formatterInput setMaximumFractionDigits:6];
//These four lines are the one fixing the issue.
NSString *formattedResultString = [formatterResult stringFromNumber: (NSNumber*)resultNumber];
NSString *formattedInputString = [formatterInput stringFromNumber:(NSNumber*)inputNumber];
NSString *formelString = [[NSString alloc]initWithFormat:
#" %# %# =", formattedInputString, convertFromName];
formelLabel.text = formelString;
NSString *resultString = [[NSString alloc]initWithFormat:
#" %# %#",formattedResultString, convertToName];
resultLabel.text = resultString;
Real arithmetic is precise. Any computer arithmetic has limited range - how many digits can be represented; and in the case of fractions inaccuracies due to the use of decimal factions by us humans and binary fractions by computers.
In your code you are using float which is a 32-bit binary floating point number with an precision of around 6 decimal digits and a range roughly from 10^-38 to 10^38. Your numbers are up to 9 digits.
Try using double thoughtout (and doubleValue etc.) which is a 64-bit binary floating point with a precision of around 15 decimal digits. You may still find the numbers don't come out as you wish, and for that you will need to look more into how to format numbers, but you should get the precision you are after.
If you need more precision, and decimal floating point as well, look at NSDecimalNumber.
See 32-bit floating point and 64-bit floating point for more details.

NSNumberFormatter Text Field Thousand Separator

I'm programming credit calculator and I want the numbers formating with the (local) thousands separator when a user enters a number.
For example 100000 should become 100.000 (local).
How can I do that in my example?
NSNumberFormatter *nf = [[[NSNumberFormatter alloc] init] autorelease];
[nf setNumberStyle: NSNumberFormatterDecimalStyle];
[nf setRoundingMode: NSNumberFormatterRoundHalfUp];
[nf setMaximumFractionDigits: 2];
double loanAmount = [[nf numberFromString: tbxLoanAmount.text] floatValue];
double intRate = [[nf numberFromString: annualInterestRate.text] floatValue];
double NRate = [[nf numberFromString: NInterestRate.text] floatValue];
double years = [[nf numberFromString: noOfYears.text] floatValue];
double residual = [[nf numberFromString: residualvalue.text] floatValue];
Thanks a lot!
D
You can try to set the followings to your number formatter:
[nf setGroupingSize:3];
[nf setCurrencyGroupingSeparator:#"."];
// you should create a string from number
NSNumber n = [NSNumber numberWithLong: 100000];
NSString str = [nf stringFromNumber: n];
NSLog(#"My number: %#", str);

How to convert NSString value #"3.45" into float?

How to convert NSString value #"3.45" into float. 3.45
float fCost = [[NSDecimalNumber decimalNumberWithString:#"3.45"]floatValue] ;
NSString *val = #"3.45";
float fCost = [val floatValue];
float number = [string floatValue];
NSString's: - (float)floatValue;
For example:
NSString *str = #"3.45";
float f = [str floatValue];
Reading your comment to Marek's answer it looks like your string actually = #"$3.45"
To convert that to a float use:
NSNumberFormatter * formatter = [[[NSNumberFormatter alloc] init] autorelease];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
formatter.currencyCode = #"USD";
float value = [[formatter numberFromString: #"$3.45"] floatValue];