Reputation: 25244
i want to floor a double by its decimal place with variable decimal length (in iphone sdk).
here some examples to show you what i mean
NSLog(@"%f",[self floorMyNumber:34.52462 toPlace:2); // should return 34.52
NSLog(@"%f",[self floorMyNumber:34.52662 toPlace:2); // should return 34.52
NSLog(@"%f",[self floorMyNumber:34.52432 toPlace:3); // should return 34.524
NSLog(@"%f",[self floorMyNumber:34.52462 toPlace:3); // should return 34.524
NSLog(@"%f",[self floorMyNumber:34.12462 toPlace:0); // should return 34.0
NSLog(@"%f",[self floorMyNumber:34.92462 toPlace:0); // should return 34.0
any ideas how to do this?
-(double)floorNumberByDecimalPlace:(float)number place:(int)place {
return (double)((unsigned int)(number * (double)pow(10.0,(double)place))) / (double)pow(10.0,(double)place);
}
Upvotes: 2
Views: 1964
Reputation: 138051
Multiply it by 10^(decimal places), cast it to an integer, then divide it by 10^(decimal places).
double floorToPlace(double number, int places)
{
int decimalPlaces = 1;
for (int i = 0; i < places; i++) divideBy *= 10;
return (int)(number * decimalPlaces) / (double)decimalPlaces;
}
Upvotes: 0
Reputation: 215261
Use sprintf (or better snprintf) to format it to a string then crop the end of the string.
Upvotes: 0
Reputation: 2991
Another solution:
placed is 10 (Example: 13.1), 100 (Example: 12.31) and so on
double value = (double)((unsigned int)(value * (double)placed)) / (double)placed
Upvotes: 1
Reputation: 2933
If you're just rounding them for the purpose of printing them, you do this with the standard printf format specifiers. For example, instead of "%f", to print 3 decimals you could use "%.3f"
Upvotes: 0