Objective C remove trailing zeros after decimal place - objective-c

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

Related

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 leading 0's and decimals

Is there any way to format an NSNumber with leading 0's and decimals? For example, I need to have the ability to write 4.5 as well as 000. Currently I have it where it will allow decimals, but not leading 0's.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSString *myString = [f numberFromString:#"4.5"];
NSLog(#"myString: %#",myString);
NSString *myOtherString = [f numberFromString:#"000"];
NSLog(#"myOtherString:%#",myOtherString);
The output from above would be: 'myString:4.5' and 'myOtherString:0'. I need to be able to do both '4.5' and '000' as output.
I have looked at Apple's "Data Formatting Guide" without much success.
Note that [f numberFromString:#"4.5"] returns an NSNumber* not a NSString*
You want something like this:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSNumber *myNumber;
NSString *myString;
myNumber = [f numberFromString:#"4.5"];
[f setNumberStyle:kCFNumberFormatterDecimalStyle];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);
myNumber = [f numberFromString:#"000"]; // Note that the extra zeros are useless
[f setFormatWidth:3];
[f setPaddingCharacter:#"0"];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);
NSLog output:
myString: 4.5
myString: 000
If you don't have strings to start with just create number like:
myNumber = [NSNumber numberWithFloat:4.5];
myNumber = [NSNumber numberWithInt:0];
Or just use standard formatting:
myString = [NSString stringWithFormat:#"%.1f", [myNumber floatValue]];
myString = [NSString stringWithFormat:#"%03d", [myNumber intValue]];
Or if you don't need an NSNumber representation just use standard formatting :
myString = [NSString stringWithFormat:#"%.1f", 4.5];
myString = [NSString stringWithFormat:#"%03d", 0];
You could try something like:
NSString *myString = [NSString stringWithFormat:#"%03f", [myNSNumber floatValue]];
This, following the printf format, will print your number forcing at least 3 digits to be printed and padding with '0's any empty space.
How about this as a variation on theme for the 000's
NSNumber *myNumber;
NSString *myString =#"000" ;
NSString * myStringResult;
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
[f setHasThousandSeparators:FALSE]; //-- remove seperator
[f setMinimumIntegerDigits:[myString length ]]; //-- set minimum number of digits to display using the string length.
myNumber = [f numberFromString:myString];
myStringResult = [f stringFromNumber:myNumber];
NSLog(#"myStringResult: %#",myStringResult);
Since this is asked often and Apple's docs suck, this is the answer that people will be looking for. The link below has two solutions. One using NSString stringWithFormat: and the other using NSNumberFormatter.
https://stackoverflow.com/a/11131497/1058199

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.

Truncate extra zeroes when formatting a float into an NSString

I am trying to format some floats as follows:
1.1500 would be displayed as “$ 1.15”
1.1000 would be displayed as “$ 1.10”
1.0000 would be displayed as “$ 1.00”
1.4710 would be displayed as “$ 1.471”
1.4711 would be displayed as “$ 1.4711”
I tried with
NSString *answer = [NSString stringWithFormat:#"$ %.2f",myvalue];
This is exactly what NSNumberFormatters are for:
float onefifteen = 1.1500; // displayed as “$ 1.15”
float oneten = 1.1000; // displayed as “$ 1.10”
float one = 1.0000; // displayed as “$ 1.00”
float onefortyseventen = 1.4710; // displayed as “$ 1.471”
float onefortyseveneleven = 1.4711; // displayed as “$ 1.4711”
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[formatter setUsesSignificantDigits:YES];
// The whole number counts as the first "significant digit"
[formatter setMinimumSignificantDigits:3];
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithFloat:onefifteen]]);
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithFloat:oneten]]);
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithFloat:one]]);
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithFloat:onefortyseventen]]);
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithFloat:onefortyseveneleven]]);
2011-12-15 19:36:52.185 SignificantCents[49282:903] $1.15
2011-12-15 19:36:52.190 SignificantCents[49282:903] $1.10
2011-12-15 19:36:52.190 SignificantCents[49282:903] $1.00
2011-12-15 19:36:52.191 SignificantCents[49282:903] $1.471
2011-12-15 19:36:52.192 SignificantCents[49282:903] $1.4711
try this :
NSString *answer = [NSString stringWithFormat:#"%.02f", myvalue];
I have figure out this. you can do this as per below implementation.
Please take a look at below demo code...
NSArray * numbers = [[NSArray alloc] initWithObjects:#"1.1500",#"1.1000",#"1.0000",#"1.4710",#"1.4711",nil];
for (int i=0; i<[numbers count]; i++) {
NSArray * floatingPoint = [[numbers objectAtIndex:i] componentsSeparatedByString:#"."];
NSString * lastObject = [[floatingPoint lastObject] stringByReplacingOccurrencesOfString:#"0" withString:#""];
if ([lastObject length] < 2) {
NSLog(#"%#",[NSString stringWithFormat:#"$ %.2f",[[numbers objectAtIndex:i] floatValue]]);
} else {
NSLog(#"%#",[NSString stringWithFormat:#"$ %g",[[numbers objectAtIndex:i] floatValue]]);
}
}
Thanks,
MinuMaster
Read the docs on format specifiers.

Need Help Rounding Numbers (Float)

In the following code, I want the the number that satisfies if (isKgs) to be rounded to one decimal point.
For example right now it is giving me 2.2643534543 but I just want 2.3.
Any ideas?
NSNumber *weightInPounds = [self.pickerArray objectAtIndex:row];
NSNumber *weightInKilos = [[DDUnitConverter massUnitConverter] convertNumber: weightInPounds fromUnit: DDMassUnitUSPounds toUnit: DDMassUnitKilograms];
NSString *temp = [NSString stringWithFormat:#"%# kgs", [weightInKilos stringValue]];
[self.firstComponentText setString:temp];
The the type of number from the picker is float, I believe.
You can format the NSNumber object using an NSNumberFormatter object. An example,
NSNumber * decimal = [NSNumber numberWithFloat:2.2643534543];
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setMaximumFractionDigits:1];
NSLog(#"%#", [formatter stringFromNumber:decimal]);