Rounding float number upto two decimal places - objective-c

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

Related

In Objective-C, exponential values from multiplying two large numbers

When multiplying two large numbers I am getting exponential values.
double price=[priceperUnit.text doubleValue];
double quantity1=[quantity.text doubleValue];
double totalvalue=price * quantity1;
totalValue.text=[NSString stringWithFormat:#"%.2f", totalvalue];
[dic setObject:#([totalValue.text floatValue]) forKey:#"Total Value"];
In dictionary I am getting these values:
PriceperUnit = 1485500;
Quantity = 9;
TotalValue = "1.33695e+07";
How to solve this issue?
As always, you should be using NSNumberFormatter for every number that you want to display to users:
double price = 1485500;
double quantity1 = 9;
double totalvalue = price * quantity1;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.minimumFractionDigits = 2;
formatter.maximumFractionDigits = 2;
totalValue.text = [formatter stringFromNumber:#(totalvalue)];
[dic setObject:#(totalvalue) forKey:#"Total Value"];
Also note that it is not a good practice to use double with money values. Operations with double are not suited for exact calculations. You should use NSDecimalNumber instead.

Rounding result to 2 decimal places

I have rounded the 'legInches' but how do I round this to 2 decimal points instead of none?
specifically - (int)round(legInches)
result = (isTitle)? #"Leg Span" : [NSString stringWithFormat:#"%dcm / %din", (int)legCentimetres, (int)round(legInches)];
The simple approach:
result = (isTitle)? #"Leg Span" : [NSString stringWithFormat:#"%dcm / %.2fin", (int)legCentimetres, legInches];
But this doesn't format the number properly for people that expect something other than a period for the decimal separator. For that you should use an NSNumberFormatter.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSString *legInchesStr = [formatter stringFromNumber:#(legInches)];
result = (isTitle)? #"Leg Span" : [NSString stringWithFormat:#"%dcm / %#in", (int)legCentimetres, legInchesStr];

Format number as percent

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.

iPhone - Rounding a float does not work

I can't achieve rounding a float.
Those calls all returns me 3.5999999 and not 3.6 for theoTimeoutTrick and theoTimeout.
How may I achieve to get that 3.6 value, into NSString AND float vars ?
#define minTimeout 1.0
#define defaultNbRetry 5
float secondsWaitedForAnswer = 20.0;
float minDelayBetween2Retry = 0.5;
int theoNbRetries = defaultNbRetry;
float theoTimeout = 0.0;
while (theoTimeout < minTimeout && theoNbRetries > 0) {
theoTimeout = (secondsWaitedForAnswer - (theoNbRetries-1)*minDelayBetween2Retry) / theoNbRetries;
theoNbRetries--;
}
float theoTimeoutTrick = [[NSString stringWithFormat:#"%.1f", theoTimeout] floatValue];
theoTimeout = roundf(theoTimeout * 10)/10.0;
From Rounding numbers in Objective-C:
float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
[formatter release];
That will get you a rounded string. You can parse it back into a float I'm sure.
Okay, here's some test code and some results:
NSLog(#"%f", round(10*3.56)/10.0);
=>3.600000
NSLog(#"%f", round(10*3.54)/10.0);
=>3.500000
NSLog(#"%f", round(10*3.14)/10.0);
=>3.100000
Okay, you know what? Your original code works as intended on my machine, OSX 10.6 and Xcode 4. How exactly are you seeing your output?

How to add commas to number every 3 digits in Objective C?

If I have a number int aNum = 2000000 how do I format this so that I can display it as the NSString 2,000,000?
Use NSNumberFormatter.
Specifically:
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:2000000]];
[formatter release];
By default NSNumberFormatter uses the current locale so the grouping separators are set to their correct values by default. The key thing is to remember to set a number style.
Don't do your own number formatting. You will almost certainly not get all the edge cases right or correctly handle all possible locales. Use the NSNumberFormatter for formatting numeric data to a localized string representation.
You would use the NSNumberFormatter instance method -setGroupingSeparator: to set the grouping separator to #"," (or better yet [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator]; thanks #ntesler) and -setGroupingSize: to put a grouping separator every 3 digits.
There's a static method on NSNumberFormatter that does just what you need:
int aNum = 2000000;
NSString *display = [NSNumberFormatter localizedStringFromNumber:#(aNum)
numberStyle:NSNumberFormatterDecimalStyle];
This way is a little more succinct than creating a new NSNumberFormatter if you don't need to do any additional configuration of the formatter.
Even easier:
NSNumber *someNumber = #(1234567890);
NSString *modelNumberString = [NSString localizedStringWithFormat:#"%#", someNumber];
NSLog(#"Number with commas: %#", modelNumberString);
coworker just taught me this today. #amazing
Think some as i will get this post looking for sample.
So if you are working with number make attention on next params:
setNumberStyle:NSNumberFormatterCurrencyStyle // if you are working with currency
It could be also
setNumberStyle:NSNumberFormatterDecimalStyle
All code is For ARC.
If you are working with Integer and need to get result such as 200,000
int value = 200000;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithInteger:value]];
If you are working with Float and need to get result such as 200,000.00
float value = 200000;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithFloat:value]];
EDIT
To have ability to use different digital separators use NSLocale.
Add to code where NSLocale is specified on Locale Identifier:
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"de_DE"]];
or use current local:
[formatter setLocale:[NSLocale currentLocale]];
Swift version
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = decimalPlaces
let result = formatter.stringFromNumber(NSNumber(double: 8.0))
By http://ios.eezytutorials.com
An easy solution could be this. My answer is almost same like #Nazir's answer but with a small trick.
double current_balance = 2000000.00;
NSNumberFormatter * formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
//[formatter setNumberStyle:NSNumberFormatterCurrencyStyle]; //if you want for currency with $ sign
[formatter setMinimumFractionDigits:2]; // Set this if you need 2 digits
[formatter setMaximumFractionDigits:2]; // Set this if you need 2 digits
NSString * currency_format = [NSString stringWithFormat:#"%#", [formatter stringFromNumber:[NSNumber numberWithDouble:current_balance]]];
For Swift 4.0
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let result = formatter.string(from: NSNumber(value: 123456))
For those who need to do it with strings of numbers and not just integers (I.e. Big Numbers) I made the following macro:
#define addCommas(__string) (\
(^NSString *(void){\
NSString *__numberString = __string;\
NSString *__integerPortion = __numberString;\
NSString *__decimalPortion = #"";\
if ([__string containsString:#"."]) {\
__integerPortion = [__numberString componentsSeparatedByString:#"."][0];\
__decimalPortion = st(#".%#", [__numberString componentsSeparatedByString:#"."][1]);\
}\
int __i = (int)__integerPortion.length-3;\
while (__i > 0) {\
__integerPortion = st(#"%#,%#", substringInRange(__integerPortion, 0, __i), substringInRange(__integerPortion, __i, (int)__integerPortion.length));\
__i -= 3;\
}\
__numberString = st(#"%#%#", __integerPortion, __decimalPortion);\
return __numberString;\
})()\
)