Objective C, Trim a float - ios

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

Related

Converting NSString number to float

I am having difficulties converting NSString's that have numbers into floats or something more useful.
I have tried the following code:
NSString *mystring = #"123"
int currentBidAmount = [myString integerValue];
No problem there.
Then float
NSString *mystring = #"123.95"
float currentBidAmount = [myString floatValue];
Again, no problem
However when myString has three decimals - I get an inaccurate number. For Example:
NSString *mystring = #"1.123.95"
float currentBidAmount = [myString floatValue];
It prints out: 1
Can someone tell me what I am doing wrong here?
The goal is to have two NSStrings - get their values and add them up for a total amount. So I need more accuracy than just I am getting now.
While you can get an NSString integer or floatValue you should use NSNumberFormatterfor that. Why? The decimal and grouping separator varies between countries and the floatValue code does only account for . as decimal separator. So users with a locale using a , are doomed.
How to:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
float myFloat = [numberFormatter numberFromString:myString].floatValue;
Read up on various settings here: https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/NSNumberFormatter_Class/Reference/Reference.html
you can't put two commas for a float value
this code works fins:
NSString *example = #"13124.4153";
float floatValue = [example floatValue];
NSLog(#"value = %f", floatValue);
Thanks for the help guys. I managed to solve the problem. The issue was the grouping separator. It separated by leaving a space. So this is why I had inaccurate numbers. Now, since I needed all my numbers to stay in this format but change when I was doing calculations (Adding sums together - I wrote a class method that looks like this:
(NSString *)getDisplayAmountStringWithValue: (NSString *)value Currency: (NSString *)currency
{
NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithString:[value stringByReplacingOccurrencesOfString:#"," withString:#""]];
if ([decimalValue isEqualToNumber:[NSDecimalNumber notANumber]]){
decimalValue = [NSDecimalNumber decimalNumberWithString:#"0"];
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:#" "];
[formatter setDecimalSeparator:#"."];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:2];
if ([currency length] > 0){
[formatter setPositivePrefix:[NSString stringWithFormat:#"%#", currency]];
[formatter setNegativePrefix:[NSString stringWithFormat:#"%#-", currency]];
}else {
[formatter setGroupingSeparator:#""];
}
NSString *newNumberString = [formatter stringFromNumber:decimalValue];
return newNumberString;
}
Notice the if statement. I simply remove the space if I don't supply a currency (Which is not needed when adding sums together) - this along with my existing code, works perfectly.
Thanks for all the tips.

iOS: NSNumberFormatter doesn't convert string back to NSNumber

I am using following NSNumberFormatter to add commas and symbol in the currency value.
self.currencyFormatter = [NSNumberFormatter new];
self.currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
self.currencyFormatter.currencySymbol = #"£";
self.currencyFormatter.currencyCode = #"GBP";
self.currencyFormatter.roundingMode = NSNumberFormatterRoundHalfUp;
self.currencyFormatter.maximumFractionDigits = 0;
Usage:
self.principleAmountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:100000]];
This displays £100,000 as expected. Now if I insert two more digits (text becomes £100,00096) in textfield and try to convert string to Integer I get 0! Basically following line returns 0. I have no idea how to deal with this issue.
NSLog(#"%d", [[self.currencyFormatter numberFromString:#"£100,00096"] integerValue]);
FYI I have custom inputview to textfield which just allows numbers to enter into textfield. In Did Edit End even I format number and display with comma.
You need to remove the commas for this to work, you can still show them in your text field but you should strip them out before you pass the string to the formatter. Something like this:
NSString *userInput = #"£100,00096";
userInput = [userInput stringByReplacingOccurrencesOfString:#"," withString:#""];
NSLog(#"%ld", (long)[[currencyFormatter numberFromString:userInput] integerValue]);
100,00096 isn't correct...
Do you mean one of these?
[[self.currencyFormatter numberFromString:#"£10000096"] integerValue]
[[self.currencyFormatter numberFromString:#"£100,000.96"] integerValue]
[[self.currencyFormatter numberFromString:#"£100000.96"] integerValue]
[[self.currencyFormatter numberFromString:#"£10,000,096"] integerValue]
My final code for the reference. The number with currency symbol also an invalid! Following takes care of everything.
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:#"%#%#", self.currencyFormatter.groupingSeparator, self.currencyFormatter.currencySymbol]];
self.amountTextField.text = [[self.amountTextField.text componentsSeparatedByCharactersInSet:doNotWant] componentsJoinedByString:#""];
self.amountTextField.text = [NSString stringWithFormat:#"£%#", self.amountTextField.text];
NSUInteger amount = [[self.currencyFormatter numberFromString:self.amountTextField.text] integerValue];
self.amountTextField.text = [self.currencyFormatter stringFromNumber:[NSNumber numberWithInteger:amount]]

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

Set UILabel character limit?

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

Removing unnecessary zeros in a simple calculator app

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.

Resources