NSNumberFormatter for rounding up float values

人走茶凉 提交于 2019-12-30 07:29:30

问题


I have a CGFloat value which I want to round to 3 digits after the decimal point. How should I do this?

Thanks.


回答1:


NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];



回答2:


If you want to go the NSDecimalNumber route, you can use the following:

NSDecimalNumber *testNumber = [NSDecimalNumber numberWithDouble:theFloat];
NSDecimalNumberHandler *roundingStyle = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:3 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *roundedNumber = [testNumber decimalNumberByRoundingAccordingToBehavior:roundingStyle];
NSString *stringValue = [roundedNumber descriptionWithLocale:[NSLocale currentLocale]];

This will use bankers' rounding to 3 decimal digits: "Round to the closest possible return value; when halfway between two possibilities, return the possibility whose last digit is even. In practice, this means that, over the long run, numbers will be rounded up as often as they are rounded down; there will be no systematic bias." Additionally, it will use a locale-specific decimal separator (".", ",", etc.).

However, if you have a numerical value like 12.5, it will return "12.5", not "12.500", which may not be what you're looking for.




回答3:


myFloat = round(myfloat * 1000) / 1000.0;



回答4:


Try formatting the float as "%5.3f" or similar for display purposes

...like Zach Langley did in his better answer.



来源:https://stackoverflow.com/questions/427210/nsnumberformatter-for-rounding-up-float-values

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