I am trying to get one digit after decimal and store it as double.
For eg : -
float A = 146.908295;
NSString * string = [NSString stringWithFormat:#"%0.01f",A]; // op 146.9
double B = [string doubleValue]; // op 146.900000
i want output as 146.9 in double or float form..,before duplicating or downvoting make sure the answer to this output is given..
Thanks
Edited:-
NSString * str = [NSString stringWithFormat:#"%0.01f",currentAngle];
tempCurrentAngle = [str doubleValue];;
tempCurrentAngle = tempCurrentAngle - 135.0;
if (tempCurrentAngle == 8.7) {
NSLog(#"DONE ");
}
here currentAngle is coming from continueTrackingWithTouch method, which will be in float..here it does not enter in if loop even when tempCurrentAngle value changes to 8.700000 .
You can compare string values instead of double like,
double currentAngle = 143.7; // I have taken static values for demo.
double tempCurrentAngle = 0.0;
NSString * str = [NSString stringWithFormat:#"%0.01f",currentAngle];
tempCurrentAngle = [str doubleValue];;
tempCurrentAngle = tempCurrentAngle - 135.0;
NSString *strToCompare = [NSString stringWithFormat:#"%0.01f",tempCurrentAngle];
if ([strToCompare isEqualToString:#"8.7"] ) {
NSLog(#"DONE ");
}
If you debug once line by line then you will get idea that why it was not entering in if caluse.
tempCurrentAngle get 143.69999999999999 when you convert str to double then you reduce 135.0 from it so it's value will be 8.6999999999999886 and then you compare it with 8.7 then it will definitely not being equal! but if you convert tempCurrentAngle string with one decimal point then it will be 8.7! so you should compare string values instead of double!
Related
In iOS I am using two strings to combine and to form a single string. But the combined string must be of 16 characters . So if two strings are small and if we combine both and if it is less than 16 characters I must add few more characters to make it to 16 characters. How to achieve this?
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
This is the code I am using. So if I combine and it is less than 16 characters how to calculate it and add more characters to make it 16 characters?
Something like below
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
if (combined.length < 16)
{
NSString *newCombined = [NSString stringWithFormat:#"%#%#", combined, #"Some new string"];
}
You can use substringWithRange: method from NSString. You can take the below code as an example and modify it as per your requirements.
if (combined.length > 25)
{
NSString *beginning = [combined substringWithRange:NSMakeRange(0, 15)];
NSString *fromEnd = [combined substringWithRange:NSMakeRange(startPoint, combined.length-startPoint)];
}
You could make use of stringWithFormat - basically of printf if you want to pad with just a single char. Below I give some examples which I have constructed to illustrate, so it won't run out the box, but you only need to comment out the ones you do not want to make it work.
// To get 50 spaces
NSString * s50 = [NSString stringWithFormat:#"%*s", 50, ""];
// Pad with these characters, select only 1
// This will pad with spaces
char * pad = "";
// This will pad with minuses - you need enough to fill the whole field
char * pad = "-------------------------------------------------------";
// Some string
NSString * s = #"Hi there";
// Here back and front are just int's. They must be, but they can be calculated,
// e.g. you could have this to pad to 50
int back = 50 - s.length; if ( back < 0 ) back = 0;
// Pad s at the back
int back = 20;
NSString * sBack = [NSString stringWithFormat:#"%#%*s", s, back, pad];
// Pad s in front
int front = 10;
NSString * sFront = [NSString stringWithFormat:#"%*s%#", front, pad, s];
// Pad s both sides
NSString * sBoth = [NSString stringWithFormat:#"%*s%#%*s", front, pad, s, back, pad];
Note that the amounts here are parameterised. I use e.g. 50 in the first line but that could just as well be n as long as n is an int and you can use that to then perform calculations, store it in n and pad. There is an example in the code.
Here is a sample of the output
2020-11-04 08:16:22.908828+0200 FormatSpecifiers[768:15293] [Hi there-------------------------------------------------------]
2020-11-04 08:16:22.908931+0200 FormatSpecifiers[768:15293] [-------------------------------------------------------Hi there]
2020-11-04 08:16:22.908992+0200 FormatSpecifiers[768:15293] [-------------------------------------------------------Hi there-------------------------------------------------------]
I just show how to pad the combined string. To combine the string of course just use stringByAppendingString e.g.
NSString * s = [a stringByAppendingString:b];
and then you can do calcs based on s.length e.g. as shown in the example.
I am new to iOS. I need to convert textfield integer value into string. I created textfield name as value1 and string as str1.
str1 = [NSString stringWithFormat:#"%d", value1];
By default, UITextField returns a NSString value.
So you can get any value like this :
NSString *str1 = value1.text;
As simple as that, but if you want to convert it to Int then,
int strInt = str1.intValue;
NSInteger strInteger = str1.integerValue;
If want to converts to a Double value,
double strDouble = str1.doubleValue;
CGFloat strCGFloat = str1.doubleValue;
And yes, if you don't need to perform anything on str1 then you shouldn't need to create an instance, you can directly convert it like this.
int strInt = value1.text.intValue;
NSInteger strInteger = value1.text.intValue;
I am making a game that requires me to use very large numbers. I believe I am able to store very large numbers with NSDecimal. However, when displaying the numbers to users I would like to be able to convert the large number to a succinct string that uses characters to signify the value eg. 100,000 -> 100k 1,000,000 -> 1.00M 4,200,000,000 -> 4.20B and so forth going up to extremely large numbers. Is there any built in method for doing so or would I have to use a bunch of
NSDecimalCompare statements to determine the size of the number and convert?
I am hoping to use objective c for the application.
I know that I can use NSString *string = NSDecimalString(&NSDecimal, _usLocale); to convert to a string could I then do some type of comparison on this string to get the result I'm looking for?
Use this method to convert your number into a smaller format just as you need:
-(NSString*) suffixNumber:(NSNumber*)number
{
if (!number)
return #"";
long long num = [number longLongValue];
int s = ( (num < 0) ? -1 : (num > 0) ? 1 : 0 );
NSString* sign = (s == -1 ? #"-" : #"" );
num = llabs(num);
if (num < 1000)
return [NSString stringWithFormat:#"%#%lld",sign,num];
int exp = (int) (log(num) / 3.f); //log(1000));
NSArray* units = #[#"K",#"M",#"G",#"T",#"P",#"E"];
return [NSString stringWithFormat:#"%#%.1f%#",sign, (num / pow(1000, exp)), [units objectAtIndex:(exp-1)]];
}
Some sample examples:
NSLog(#"%#",[self suffixNumber:#99999]); // 100.0K
NSLog(#"%#",[self suffixNumber:#5109999]); // 5.1M
Source
Solved my issue: Can only be used if you know that your NSDecimal that you are trying to format will only be a whole number without decimals so make sure you round when doing any math on the NSDecimals.
-(NSString *)returnFormattedString:(NSDecimal)nsDecimalToFormat{
NSMutableArray *formatArray = [NSMutableArray arrayWithObjects:#"%.2f",#"%.1f",#"%.0f",nil];
NSMutableArray *suffixes = [NSMutableArray arrayWithObjects:#"k",#"M",#"B",#"T",#"Qa",#"Qi",#"Sx",#"Sp",#"Oc",#"No",#"De",#"Ud",#"Dud",#"Tde",#"Qde",#"Qid",#"Sxd",#"Spd",#"Ocd",#"Nvd",#"Vi",#"Uvi",#"Dvi",#"Tvi", nil];
int dick = [suffixes count];
NSLog(#"count %i",dick);
NSString *string = NSDecimalString(&nsDecimalToFormat, _usLocale);
NSString *formatedString;
NSUInteger characterCount = [string length];
if (characterCount > 3) {
NSString *trimmedString=[string substringToIndex:3];
float a;
a = 100.00/(pow(10, (characterCount - 4)%3));
int remainder = (characterCount-4)%3;
int suffixIndex = (characterCount + 3 - 1)/3 - 2;
NSLog(#"%i",suffixIndex);
if(suffixIndex < [suffixes count]){
NSString *formatSpecifier = [formatArray[remainder] stringByAppendingString:suffixes[suffixIndex]];
formatedString= [NSString stringWithFormat:formatSpecifier, [trimmedString floatValue] / a];
}
else {
formatedString = #"too Big";
}
}
else{
formatedString = string;
}
return formatedString;
}
I have to count how many decimal digits are there in a double in Xcode 5. I know that I must convert my double in a NSString, but can you explain me how could I exactly do? Thanks
A significant problem is that a double has a fractional part which has no defined length. If you know you want, say, 3 fractional digits, you could do:
[[NSString stringWithFormat:#"%1.3f", theDoubleNumber] length]
There are more elegant ways, using modulo arithmetic or logarithms, but how elegant do you want to be?
A good method could be to take your double value and, for each iteration, increment a counter, multiply your value by ten, and constantly check if the left decimal part is really near from zero.
This could be a solution (referring to a previous code made by Graham Perks):
int countDigits(double num) {
int rv = 0;
const double insignificantDigit = 8;
double intpart, fracpart;
fracpart = modf(num, &intpart);
while ((fabs(fracpart) > 0.000000001f) && (rv < insignificantDigit))
{
num *= 10;
fracpart = modf(num, &intpart);
rv++;
}
return rv;
}
You could wrap the double in an instance of NSNumber and get an NSString representation from the NSNumber instance. From there, calculating the number of digits after the decimal could be done.
One possible way would be to implement a method that takes a double as an argument and returns an integer that represents the number of decimal places -
- (NSUInteger)decimalPlacesForDouble:(double)number {
// wrap double value in an instance of NSNumber
NSNumber *num = [NSNumber numberWithDouble:number];
// next make it a string
NSString *resultString = [num stringValue];
NSLog(#"result string is %#",resultString);
// scan to find how many chars we're not interested in
NSScanner *theScanner = [NSScanner scannerWithString:resultString];
NSString *decimalPoint = #".";
NSString *unwanted = nil;
[theScanner scanUpToString:decimalPoint intoString:&unwanted];
NSLog(#"unwanted is %#", unwanted);
// the number of decimals will be string length - unwanted length - 1
NSUInteger numDecimalPlaces = (([resultString length] - [unwanted length]) > 0) ? [resultString length] - [unwanted length] - 1 : 0;
return numDecimalPlaces;
}
Test the method with some code like this -
// test by changing double value here...
double testDouble = 1876.9999999999;
NSLog(#"number of decimals is %lu", (unsigned long)[self decimalPlacesForDouble:testDouble]);
results -
result string is 1876.9999999999
unwanted is 1876
number of decimals is 10
Depending on the value of the double, NSNumber may do some 'rounding trickery' so this method may or may not suit your requirements. It should be tested first with an approximate range of values that your implementation expects to determine if this approach is appropriate.
I have a text field in an xib file. In a method in the .m file, I can print the contents of the text field, but I cannot get those contents converted to a float. The text field is formatted with commas, as in 123,456,789. Below is the code snippet, where datacellR2C2 is the textfield.
float originalValue2 = originalValue2 = [datacellR2C2.text floatValue];
NSLog(#"datacellR2C2 as text --> %# <---\n",datacellR2C2.text); // this correctly shows the value in datacellR2C2
NSLog(#"originalValue2 = %f <--\n", originalValue2); // this incorrectly returns the value 1.0
I would appreciate any suggestions for a fix or a direction where I should look for the problem.
In the declaration for -floatValue a comment is shown:
/* The following convenience methods all skip initial space characters
(whitespaceSet) and ignore trailing characters. NSScanner can be used
for more "exact" parsing of numbers.
*/
Ergo, commas cause truncation, because they are trailing chars. Even the string you provided (123,456,789) only prints 123.000, because that's all -floatValue sees.
//test
NSString *string = #"123,456,789";
float originalValue2 = [string floatValue];
NSLog(#"datacellR2C2 as text --> %# <---\n",string); // this correctly shows the value in datacellR2C2
NSLog(#"originalValue2 = %f <--\n", originalValue2);
//log
2012-07-07 22:16:15.913 [5709:19d03] datacellR2C2 as text --> 123,456,789 <---
2012-07-07 22:16:15.916 [5709:19d03] originalValue2 = 123.000000 <--
Just get rid of them with a simple +stringByReplacingOccurrencesOfString:withString:, and remove those trailing commas:
//test
NSString *string = #"123,456,789";
NSString *cleanString = [string stringByReplacingOccurrencesOfString:#"," withString:#""];
float originalValue2 = [cleanString floatValue];
NSLog(#"datacellR2C2 as text --> %# <---\n",cleanString); // this correctly shows the value in datacellR2C2
NSLog(#"originalValue2 = %f <--\n", originalValue2);
//log
2012-07-07 22:20:20.737 [5887:19d03] datacellR2C2 as text --> 123456789 <---
2012-07-07 22:20:20.739 [5887:19d03] originalValue2 = 123456792.000000 <--
By the way, a float is rounding that string up to an even number, use double precision instead.