floor double by decimal place

前提是你 提交于 2020-01-04 09:25:14

问题


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


来源:https://stackoverflow.com/questions/3273179/floor-double-by-decimal-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!