I want to know if there is a simple function that I can use such this sample. I have a
float value = 1.12345;
I want to round it with calling something like
float value2 = [roundFloat value:value decimal:3];
NSLog(@"value2 = %f", value2);
And I get "1.123"
Is there any Library
or default function for that or I should write a code block for this type of calculations?
thank for your help in advance
Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.
You can try ceil() and floor() to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil() and floor() only work on double s though. EDIT: Also, for floats, you can use truncf() to truncate floats.
Float number always round up.
Using NSLog(@"%f", theFloat)
always outputs six decimals, for example:
float theFloat = 1;
NSLog(@"%f",theFloat);
Output:
1.000000
In other words, you will never get 1.123
by using NSLog(@"%f", theFloat)
.
Cut-off after three decimals:
float theFloat = 1.23456;
float newFLoat = (int)(theFloat * 1000.0) / 1000.0;
NSLog(@"%f",newFLoat);
Output:
1.234000
Round to three decimals (using roundf()
/ lroundf()
/ ceil()
/ floor()
):
float theFloat = 1.23456;
float newFLoat = (int)(roundf(theFloat * 1000.0)) / 1000.0;
NSLog(@"%f",newFLoat);
Output:
1.235000
Round to three decimals (dirty way):
float theFloat = 1.23456;
NSString *theString = [NSString stringWithFormat:@"%.3f", theFloat];
float newFloat = [theString floatValue];
NSLog(@"%@",theString);
NSLog(@"%f",newFloat);
Output:
1.235
1.235000
For printing the value use:
NSLog(@"value2 = %.3f", value2);
Rounding to 3 decimal digits before calculations doesn't really make sense because float
is not a precise number. Even if you round it to 1.123
, it will be something like 1.122999999998
.
Rules:
NSDecimalNumber
or fixed point arithmetics.Floating point numbers don't have decimal places, they have binary places. Decimal-radix numbers have decimal places. You can't round floating point numbers to specific numbers of decimal places unless you convert to a decimal radix. No routine, method, function etc., that returns a floating point value can possibly carry out this task.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With