I have an app that imports a long list of data of a csv.
I need to work with the numbers fetched, but in order to do this, I need to get rid of the decimal place on numbers that are ints, and leave untoched numbers that have x.5 as decimal
for example
1.0 make it 1
1.50 make it 1.5
what would be the best way to accomplish this?
thanks a lot!
You can use modf to check if the fraction part equates to zero or not.
-(BOOL)isWholeNumber:(double)number
{
double integral;
double fractional = modf(number, &integral);
return fractional == 0.00 ? YES : NO;
}
Will work for some boundary cases as well.
float a = 15.001;
float b = 16.0;
float c = -17.999999;
NSLog(#"a %#", [self isWholeNumber:a] ? #"YES" : #"NO");
NSLog(#"b %#", [self isWholeNumber:b] ? #"YES" : #"NO");
NSLog(#"c %#", [self isWholeNumber:c] ? #"YES" : #"NO");
Output
a NO
b YES
c NO
Other solutions do not work if the number is very close to a whole number. I am not sure if you have this requirement.
After that you can display them as you like using the NSNumberFormatter, one for whole numbers and one for fractions.
A simple NSNumberFormatter should achieve this for you:
float someFloat = 1.5;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setAllowsFloats:YES];
[formatter setMaximumFractionDigits:1];
NSString *string = [formatter stringFromNumber:[NSNumber numberWithFloat:someFloat]];
Of course this assumes that you only have decimals in the tenths that you want to keep, for example if you used "1.52" this would return "1.5" but judging by your last post on rounding numbers to ".5" this shouldn't be a problem.
This code achieves what you want
float value1 = 1.0f;
float value2 = 1.5f;
NSString* formattedValue1 = (int)value1 == (float)value1 ? [NSString stringWithFormat:#"%d", (int)value1] : [NSString stringWithFormat:#"%1.1f", value1];
NSString* formattedValue2 = (int)value2 == (float)value2 ? [NSString stringWithFormat:#"%d", (int)value2] : [NSString stringWithFormat:#"%1.1f", value2];
This kind of thing could be done in a category so how about
// untested
#imterface NSString (myFormats)
+(NSString)formattedFloatForValue:(float)floatValue;
#end
#implementation NSString (myFormats)
+(NSString)formattedFloatForValue:(float)floatValue
{
return (int)floatValue == (float)floatValue ? [NSString stringWithFormat:#"%d", (int)floatValue] : [NSString stringWithFormat:#"%1.1f", floatValue];
}
#end
// usage
NSLog(#"%#", [NSString formattedFloatForValue:1.0f]);
NSLog(#"%#", [NSString formattedFloatForValue:1.5f]);
Related
I have float like 3500,435232123. All I want to know if exists (in Objective C) a function that let me keep just the last 4 digits in my case is 2123.
You can use NSNumberFormatter
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:4];
[format setMinimumFractionDigits:4];
string = [NSString stringWithFormat:#"%#",[format stringFromNumber:[NSNumber numberWithFloat:65.50055]] ;
Or simply
NSString *string = [NSString stringWithFormat:#"%.04f", floatValue];
If you want only last four digits, convert the float to a string
NSString *string = [NSString stringWithFormat:#"%f", floatValue];
and get the last four characters
NSString *lastFour = [string substringFromIndex: [string length] - 4];
It you want to get the decimal part, you can do x - floor(x). For instance:
float x = 3500,435232123;
NSString *string = [NSString stringWithFormat:#"%.04f", x - floor(x)];
And to get 4 decimal digits do what Fawad Masud says.
No there is no such function, as far as i know. But here is a way to achieve exactly what you want.
First you have to round it to four digits after point:
NSString *exampleString = [NSString stringWithFormat:#"%.04f", valueToRound];
Then you get the location for the comma inside the exampleString:
NSRange commaRange = [valueString rangeOfString:#","];
Finally you create the finalString with the values from that NSRange. The substring starts at commaRange.location+commaRange.lengthbecause thats the index directly after the comma.
NSString *finalString = [valueString substringWithRange:NSMakeRange(commaRange.location+commaRange.length,valueString.length-commaRange.location-commaRange.length)];
Hope that helps you.
I think is no predefined function for that.
and the solution i thought of is:
float floatNum = 3500.435232123;
converting float number to string and trim/substring the string, like for example:
NSString *stringFloat = [NSString stringWithFormat:#"%f", floatNum];
NSString *newString = [stringFloat substringWithRange:NSMakeRange(stringFloat.length - 4, stringFloat.length)];
NSLog(#"%#", newString);
another is something like:
NSString *stringFloat = [NSString stringWithFormat:#"%f", floatNum];
//separates the floating number to
arr[0] = whole number
arr[1] = decimals
NSArray *arr=[str componentsSeparatedByString:#"."];
since you just want to work on the decimal, i think arr[1] is what you need..
NSString *stringDecimals = (NSString *)arr[1];
if ( stringDecimals.length > 4) //check the length of the decimals then cut if exceeds 4 character..
{
stringDecimals = [stringDecimals substringWithRange:NSMakeRange(stringDecimals.length - 4, stringDecimals.length)];
}
NSLog(#"stringDecimals: %#", stringDecimals);
I want the concatenated NSString I have to be output in the format "00:00", the 0s being the digits in the concatenated string. And if there are not enough characters in the NSString, the other digits are made to be 0.
And if there are more than 4 digits than I want to only have the furthest right digits.
I have done this in Java before, I am assuming it's possible in Objective-C as well.
UIButton *button = sender;
NSString *concatenated = [self.input stringByAppendingString: button.titleLabel.text];
self.input = concatenated;
self.userOutput.text = self.input;
For example, I might get "89" as my concatenated string. I then want, self.input = 00:89.
OR
if I get 89374374 from my concatenated string, I then want self.input = 43:74.
I hope I am being clear
The following method should give the desired output:
- (NSString *)getFormattedTimeStringFromString:(NSString *)string
{
int input = [string intValue];
int mins = input % 100;
input /= 100;
int hours = input % 100;
return [NSString stringWithFormat:#"%02d:%02d", hours, mins];
}
You can use this by calling
self.input = [self getFormattedTimeStringFromString:concatenated];
Like this:
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSString *dateTimeStr = [df stringFromDate:[NSDate date]];
if ([concatenated length] == 2) {
self.input = [NSString stringWithFormat:#"00:%#",concatenated];
}
else
{
NSString *test = [concatenated substringFromIndex:[concatenated length] -4];
self.input = [NSString stringWithFormat:#"%#:%#",[test substringToIndex:2],[test substringFromIndex:[test length]-2]];
}
Please try above code it will fail if [concatenated length] is 3 or 1 , modify it accordingly
I start off with a number, lets say 250. I add all sorts of numbers, but anytime I add a high number like 2,000 it adds correctly. Then I add 3. The new number comes out to 5 like it thought 2,000 was 2.0. I do not know why it is doing this.
float start = self.amountLabel.text.floatValue;
float changeAmount = self.amountField.text.floatValue;
float newValue;
if (determConfirm == 1) {
newValue = start + changeAmount;
} else {
newValue = start - changeAmount;
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:5];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:newValue]];
[[NSUserDefaults standardUserDefaults] setValue:numberString forKey:#"newValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.amountLabel.text = numberString;
self.amountField.text = #"0.00";
[self.amountField resignFirstResponder];
The problem is the use of floatValue to convert the formatted number text to a number. floatValue only works as expected if the text is unformatted (no commas) and uses the period for the decimal separator.
Since you store a formatted number in the field, it only works with small numbers and in certain locales.
Replace your use of floatValue on the text with the same NSNumberFormatter used to format the number. Use it to parse the text and give you an NSNumber (which you can then call floatValue on).
Just a guess as it's hard by looking at your code, but maybe you want this:
float newValue = start;
if (determConfirm == 1) {
newValue += changeAmount;
} else {
newValue -= changeAmount;
}
I have a UILabel that shows the outside temperature, the problem is, sometimes it shows it as a XX.XXº format instead of the normal XXº or XXXº format used to show temperature, is there anyway to force the label to only show the temperature without the decimals or at least force it to only be able to use 2 characters?
You can use this to eliminate the decimals:
NSString* numberString = [NSString stringWithFormat:#"%.0f", d]; // 0 means no decimals
Otherwise I believe this will work to limit the number of chars to 2:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.usesSignificantDigits = YES;
formatter.maximumSignificantDigits = 2;
I have not really used NSNumberFormatter very much though.
NSString *temp = [galleryEntryTree objectForKey:#"description"];
if ([temp length] > 500) {
NSRange range = [temp rangeOfComposedCharacterSequencesForRange:(NSRange){0, 500}];
temp = [temp substringWithRange:range];
temp = [temp stringByAppendingString:#" …"];
}
coverView.label2.text = temp;
You may also use substring method
NSString *newformat = [NSString stringWithFormat:#"%#",[temperature substringWithRange:NSMakeRange(0,2)]];
In this case temperature is a string that you set for your label and you are only retrieving the 1st 2 digits only
I made a simple calculator and Everytime I hit calculate it'll give a an answer but gives six unnecessary zeros, my question, how can I remove those zeros?
NSString *firstString = textfieldone.text;
NSString *secondString = textfieldtwo.text;
NSString *LEGAL = #"0123456789";
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];
NSString *filteredOne = [[firstString componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
NSString *filteredTwo = [[secondString componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
firstString = filteredOne;
secondString = filteredTwo;
//Here we are creating three doubles
double num1;
double num2;
double output;
//Here we are assigning the values
num1 = [firstString doubleValue];
num2 = [secondString doubleValue];
output = num1 + num2;
label.text = [NSString stringWithFormat:#"%f",output];
Example:
15 + 15 = 30.000000
I want to add that none of that is necessary if you use the %g specifier.
If you're displaying this by using a string, check the following approaches.
NSString
NSString * display = [NSString stringWithFormat:#"%f", number];
//This approach will return 30.0000000
NSString * display = [NSString stringWithFormat:#"%.2f", number];
//While this approach will return 30.00
Note: You can specify the number of decimals you want to return by adding a point and a number before the 'f'
-Edited-
In your case use the following approach:
label.text = [NSString stringWithFormat:#"%.0f", output];
//This will display your result with 0 decimal places, thus giving you '30'
Please try this out. This should suit your requirements completely.
NSString * String1 = [NSString stringWithFormat:#"%f",output];
NSArray *arrayString = [String1 componentsSeperatedByString:#"."];
float decimalpart = 0.0f;
if([arrayString count]>1)
{
decimalpart = [[arrayString objectAtIndex:1] floatValue];
}
//This will check if the decimal part is 00 like in case of 30.0000, only in that case it would strip values after decimal point. So output will be 30
if(decimalpart == 0.0f)
{
label.text = [NSString stringWithFormat:#"%.0f", output];
}
else if(decimalpart > 0.0f) //This will check if the decimal part is 00 like in case of 30.123456, only in that case it would shows values upto 2 digits after decimal point. So output will be 30.12
{
label.text = [NSString stringWithFormat:#"%.02f",output];
}
Let me know if you need more help.
Hope this helps you.