NSNumberFormatter for rounding up float values

后端 未结 4 659
孤城傲影
孤城傲影 2021-01-07 05:06

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

Thanks.

相关标签:
4条回答
  • 2021-01-07 05:17
    NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];
    
    0 讨论(0)
  • 2021-01-07 05:17
    myFloat = round(myfloat * 1000) / 1000.0;
    
    0 讨论(0)
  • 2021-01-07 05:28

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

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

    0 讨论(0)
  • 2021-01-07 05:39

    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.

    0 讨论(0)
提交回复
热议问题