Round double in Objective-C - objective-c

I want to round a double to one decimal place in Objective-C.
In Swift I can do it with an extension:
public extension Double {
/// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
However, apparently you cannot call extensions on primitives from Objective-C so I can't use the extension.
I would be happy to do the rounding either on the double directly or as a string, however, neither of the following is working:
double mydub = 122.12022222223322;
NSString *axtstr = [NSString stringWithFormat:#"%2f", mydub]; //gives 122.120222
double rounded = (round(mydub*10)) / 10.0; //gives 122.100000
How do I convert 122.12022222223322; into 122.1?

You need to put a decimal between the % and 2f
[NSString stringWithFormat:#"%.2f", mydub];

double mydouble = 122.12022222223322;
NSString *str = [NSString stringWithFormat:#"%.2f", mydouble];
// = #"122.12"
.. will not round mydouble. Instead it will only apply format to the output as string.
double d = 122.49062222223322;
NSString *dStr = [NSString stringWithFormat:#"%.f %.1f %.2f %.3f", d, d, d, d];
// = #"122 122.5 122.49 122.491"
As Objective-C shares the language rules from C you can round safely with
#include <math.h>
double rounded = round(mydouble);
// = 122.000000
of course you can shift comma with multiplication and dividing the power of ten you want.
double commashifted = round(mydouble*100.0)/100.0;
// = 122.120000;
If you are really into Objective-C Classes to do same in deluxe have a look into 'NSDecimal.h' in the Foundation Framework.
Last but not least you can do the same with C as you did with swift.
double roundbycomma(int commata, double zahl) {
double divisor = pow(10.0, commata);
return round(zahl * divisor) / divisor;
}

Related

Objective-C: Flooring to 3 decimals correctly

I am trying to floor a float value to the third decimal. For example, the value 2.56976 shall be 2.569 not 2.570. I searched and found answers like these:
floor double by decimal place
Such answers are not accurate. For example the code:
double value = (double)((unsigned int)(value * (double)placed)) / (double)placed
can return the value - 1 and this is not correct. The multiplication of value and placed value * (double)placed) could introduce something like: 2100.999999996. When changed to unsigned int, it becomes 2100 which is wrong (the correct value should be 2101). Other answers suffer from the same issue. In Java, you can use BigDecimal which saves all that hassels.
(Note: of course, rounding the 2100.9999 is not an option as it ruins the whole idea of flooring to "3 decimals correctly")
The following code should work:
#include <stdio.h>
#include <math.h>
int main(void) {
double value = 1.23456;
double val3;
val3 = floor(1000.0 * value + 0.0001) * 0.001; // add 0.0001 to "fix" binary representation problem
printf("val3 is %.8f; the error is %f\n", val3, 1.234 - val3);
}
this prints out
val3 is 1.23400000; the error is 0.000000
If there are any residual errors, it comes about from the fact that floating point numbers cannot necessarily be represented exactly - the idea behind BigDecimal and things like that is to work around that in a very explicit way (for example by representing a number as its digits, rather than a binary representation - it's less efficient, but maintains accuracy)
I had to consider a solution involving NSString and it worked like a charm. Here is the full method:
- (float) getFlooredPrice:(float) passedPrice {
NSString *floatPassedPriceString = [NSString stringWithFormat:#"%f", passedPrice];
NSArray *floatArray = [floatPassedPriceString componentsSeparatedByString:#"."];
NSString *fixedPart = [floatArray objectAtIndex:0];
NSString *decimalPart = #"";
if ([floatArray count] > 1) {
NSString *decimalPartWhole = [floatArray objectAtIndex:1];
if (decimalPartWhole.length > 3) {
decimalPart = [decimalPartWhole substringToIndex:3];
} else {
decimalPart = decimalPartWhole;
}
}
NSString *wholeNumber = [NSString stringWithFormat:#"%#.%#", fixedPart, decimalPart];
return [wholeNumber floatValue];
}
For example, the value 2.56976 shall be 2.569 not 2.570
Solution is has simple as that :
double result = floor(2.56976 * 1000.0) / 1000.0;
I don't know why you search complication... this works perfectly, doesn't need to pass by some unsigned int or other + 0.0001 or whatever.
Important note :
NSLog(#"%.4f", myDouble);
Actually do a round on your variable. So it's improper to believe you can floor with a %.Xf

Double division loses decimal places in objective-c

What do I have to do to have more than just one decimal place when dividing floats and doubles.
The code is:
double *dbl; //In fact this is a parameter of the function
double *kg;
double total = 41.2;
*dbl = *kg * 1000.0l / total;
In my case, *kg = 2485 and total = 41.2. So, the result should be someting like 60315.5339805. However, I only get 60315.5. What do I have to do in order not to lose the rest of the decimal digits.
I know I can use NSNumber, but when I convert to double using doubleValue, I always get 60315.5.
Thank you in advance.
This works fine for me:
- (void) myFunc:(double *)dbl
{
double kg = 2485;
double total = 41.2;
*dbl = kg * 1000.0l / total;
}
- (void)viewDidLoad
{
[super viewDidLoad];
double d;
[self myFunc:&d];
NSLog(#"%lf",d);
}

Objective C - how to convert Degree-Minute-Second to Double

My actual problem is - How to obtain a CLLocation Object when the coordinate value on the map is available in Degree-Minute-Second form (as a String), instead of Double.
So, I am Looking for a way to convert Degree-Minute-Second to Double, which i can use to form a CLLocation object.
I came up with a bit of a cleaner answer when figuring this out
// split the string to deal with lat and lon separately
NSArray *parts = [dmsString componentsSeparatedByString:#","];
NSString *latStr = parts[0];
NSString *lonStr = parts[1];
// convert each string
double lat = [self degreesStringToDecimal:latStr];
double lon = [self degreesStringToDecimal:lonStr];
// init your location object
CLLocation *loc = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
The magic
- (double)degreesStringToDecimal:(NSString*)string
{
// split the string
NSArray *splitDegs = [string componentsSeparatedByString:#"\u00B0"]; // unicode for degree symbol
NSArray *splitMins = [splitDegs[1] componentsSeparatedByString:#"'"];
NSArray *splitSecs = [splitMins[1] componentsSeparatedByString:#"\""];
// get each segment of the dms string
NSString *degreesString = splitDegs[0];
NSString *minutesString = splitMins[0];
NSString *secondsString = splitSecs[0];
NSString *direction = splitSecs[1];
// convert degrees
double degrees = [degreesString doubleValue];
// convert minutes
double minutes = [minutesString doubleValue] / 60; // 60 degrees in a minute
// convert seconds
double seconds = [secondsString doubleValue] / 3600; // 60 seconds in a minute, or 3600 in a degree
// add them all together
double decimal = degrees + minutes + seconds;
// determine if this is negative. south and west would be negative values
if ([direction.uppercaseString isEqualToString:#"W"] || [direction.uppercaseString isEqualToString:#"S"])
{
decimal = -decimal;
}
return decimal;
}
Note that I've only tested this with coordinates in Wisconsin, which is North and West. I'm using this tool to verify my calculations.
Let's say you have a the coordinate value in a String -
Split the String To obtain Degree-Minute-Second values in separate strings.
NSString *longlat= #"+39° 44' 39.28", -104° 50' 5.86" "(find a way to escape the " in the string)
//separate lat and long
NSArray *splitLonglat = [longlat componentsSeparatedByString:#","];
//separate Degree-Minute-Seconds
NSArray *arrayLat = [[splitLonglat objectAtIndex:0] componentsSeparatedByString:#" "];
double latitude,longitude;
if([arrayLat count]==3){
//get the double value for latitude
latitude= [self convertDMSToDD_deg:(NSString *)[arrayLat objectAtIndex:0]//degree
min:(NSString *)[arrayLat objectAtIndex:1]//minute
sec:(NSString *)[arrayLat objectAtIndex:2]//seconds
];
}else{
//some values could be in decimal form in the String already, instead of Degree-Minute-Second form and we might not need to convert them.
NSLog(#"latitude in decimal for %#",locationModelObject.name);
latitude=[[splitLonglat objectAtIndex:0]doubleValue];
}
NSArray *arrayLong= [[splitLonglat objectAtIndex:1] componentsSeparatedByString:#" "];
if([arrayLong count]==4){
//get the double value for longitude
longitude= [self convertDMSToDD_deg:(NSString *)[arrayLong objectAtIndex:1]//degree
min:(NSString *)[arrayLong objectAtIndex:2]//minute
sec:(NSString *)[arrayLong objectAtIndex:3]//seconds
];
}else{
//some values could be in decimal form in the String already, instead of Degree-Minute-Second form and we might not need to convert them.
NSLog(#"longitude in decimal for %#",locationModelObject.name);
longitude=[[splitLonglat objectAtIndex:1]doubleValue];
}
//add latitude longitude to the model object
locationModelObject.latitude=latitude;
locationModelObject.longitude=longitude;
The Method which does the conversion
-(double) convertDMSToDD_deg:(NSString*)degrees min:(NSString* )minutes sec:(NSString*)seconds {
int latsign=1;
double degree=[degrees doubleValue];
double minute=[minutes doubleValue];
double second=[seconds doubleValue];
if (degree<0){
latsign = -1;
}
else{
latsign=1;
}
double dd = (degree + (latsign* (minute/60.)) + (latsign* (second/3600.) ) ) ;
return dd;
}

speed up this Standard Deviation method

I have this method to calculate the standard deviation of an array of NSNumber integers, given a mean. The calculation uses NSDecimals to retain the highest resolution. This is currently demanding many cpu cycles, any help to speed it up while retaining the resolution required is appreciated! Thank you.
-(NSDecimal)standardDeviationOf:(NSMutableArray *)array withMean:(NSDecimal)mean {
if (![array count]) return CPTDecimalFromInt(0);
NSDecimal sumOfSquaredDifferences = CPTDecimalFromInt(0);
for (NSNumber *number in array) {
NSDecimal valueOfNumber = CPTDecimalFromInt([number intValue]);
NSDecimal difference = CPTDecimalSubtract(valueOfNumber, mean);
sumOfSquaredDifferences = CPTDecimalAdd(sumOfSquaredDifferences, CPTDecimalMultiply(difference, difference));
}
return CPTDecimalFromDouble(
sqrt(
CPTDecimalDoubleValue(sumOfSquaredDifferences) / [[NSNumber numberWithInt:[array count]] doubleValue]
)
);
}
An NSDecimal has 38 digits of precision, whereas double has roughly 16 digits of precision. But at the end of your loop, when you convert sumOfSquaredDifferences to double for the sqrt function, all the extra precision you had in the NSDecimal is "lost". You might as well perform the arithmetic of your inner loop using double, which should be much faster than NSDecimal:
double sumOfSquaredDifferences = 0;
double valueOfMean = [mean doubleValue];
for (NSNumber *number in array) {
double valueOfNumber = [number intValue];
double difference = valueOfNumber - valueOfMean;
sumOfSquaredDifferences += difference * difference;
}
return CPTDecimalFromDouble(sqrt(sumOfSquaredDifferences /
double([array count])));

Make a float only show two decimal places

I have the value 25.00 in a float, but when I print it on screen it is 25.0000000.
How can I display the value with only two decimal places?
It is not a matter of how the number is stored, it is a matter of how you are displaying it. When converting it to a string you must round to the desired precision, which in your case is two decimal places.
E.g.:
NSString* formattedNumber = [NSString stringWithFormat:#"%.02f", myFloat];
%.02f tells the formatter that you will be formatting a float (%f) and, that should be rounded to two places, and should be padded with 0s.
E.g.:
%f = 25.000000
%.f = 25
%.02f = 25.00
Here are few corrections-
//for 3145.559706
Swift 3
let num: CGFloat = 3145.559706
print(String(format: "%f", num)) = 3145.559706
print(String(format: "%.f", num)) = 3145
print(String(format: "%.1f", num)) = 3145.6
print(String(format: "%.2f", num)) = 3145.56
print(String(format: "%.02f", num)) = 3145.56 // which is equal to #"%.2f"
print(String(format: "%.3f", num)) = 3145.560
print(String(format: "%.03f", num)) = 3145.560 // which is equal to #"%.3f"
Obj-C
#"%f" = 3145.559706
#"%.f" = 3146
#"%.1f" = 3145.6
#"%.2f" = 3145.56
#"%.02f" = 3145.56 // which is equal to #"%.2f"
#"%.3f" = 3145.560
#"%.03f" = 3145.560 // which is equal to #"%.3f"
and so on...
You can also try using NSNumberFormatter:
NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = #"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];
You may need to also set the negative format, but I think it's smart enough to figure it out.
I made a swift extension based on above answers
extension Float {
func round(decimalPlace:Int)->Float{
let format = NSString(format: "%%.%if", decimalPlace)
let string = NSString(format: format, self)
return Float(atof(string.UTF8String))
}
}
usage:
let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true
In Swift Language, if you want to show you need to use it in this way. To assign double value in UITextView, for example:
let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)
If you want to show in LOG like as objective-c does using NSLog(), then in Swift Language you can do this way:
println(NSString(format:"%.2f", result))
IN objective-c, if you are dealing with regular char arrays (instead of pointers to NSString) you could also use:
printf("%.02f", your_float_var);
OTOH, if what you want is to store that value on a char array you could use:
sprintf(your_char_ptr, "%.02f", your_float_var);
The problem with all the answers is that multiplying and then dividing results in precision issues because you used division. I learned this long ago from programming on a PDP8.
The way to resolve this is:
return roundf(number * 100) * .01;
Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.
What level of precision you want is up to you. Just don't divide the product, multiply it by the decimal equivalent.
No funny String conversion required.
in objective -c is u want to display float value in 2 decimal number then pass argument indicating how many decimal points u want to display
e.g 0.02f will print 25.00
0.002f will print 25.000
Here's some methods to format dynamically according to a precision:
+ (NSNumber *)numberFromString:(NSString *)string
{
if (string.length) {
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
return [f numberFromString:string];
} else {
return nil;
}
}
+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
NSNumber *numberValue = [self numberFromString:string];
if (numberValue) {
NSString *formatString = [NSString stringWithFormat:#"%%.%ldf", (long)precision];
return [NSString stringWithFormat:formatString, numberValue.floatValue];
} else {
/* return original string */
return string;
}
}
e.g.
[TSPAppDelegate stringByFormattingString:#"2.346324" toPrecision:4];
=> 2.3453
[TSPAppDelegate stringByFormattingString:#"2.346324" toPrecision:0];
=> 2
[TSPAppDelegate stringByFormattingString:#"2.346324" toPrecision:2];
=> 2.35 (round up)
Another method for Swift (without using NSString):
let percentage = 33.3333
let text = String.localizedStringWithFormat("%.02f %#", percentage, "%")
P.S. this solution is not working with CGFloat type only tested with Float & Double
Use NSNumberFormatter with maximumFractionDigits as below:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(#"%#", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);
And you will get 12.35
If you need to float value as well:
NSString* formattedNumber = [NSString stringWithFormat:#"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);
lblMeter.text=[NSString stringWithFormat:#"%.02f",[[dic objectForKey:#"distance"] floatValue]];