floor double by decimal place

2019-07-15 07:44发布

问题:

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?

solution

-(double)floorNumberByDecimalPlace:(float)number place:(int)place {
    return (double)((unsigned int)(number * (double)pow(10.0,(double)place))) / (double)pow(10.0,(double)place);
}

回答1:

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



回答2:

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"



回答3:

Use sprintf (or better snprintf) to format it to a string then crop the end of the string.



回答4:

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