How to specify decimal places when formatting NSNumber objects?

前端 未结 3 925
时光取名叫无心
时光取名叫无心 2020-12-31 15:12

I\'m using the following piece of Objective-C code to format a NSNumber, and it works fine most of the time, but it doesn\'t quite do what I want when the NSNumber object ho

相关标签:
3条回答
  • 2020-12-31 16:00

    I believe what you are looking for is: "%.2f"

    Worst case scenario, you can split the value, check if there is anything after the decimal. If there isn't add the 00 by hand?

    0 讨论(0)
  • 2020-12-31 16:16

    Your format string should have a "0" for each decimal place you want to always exist.

    [formatter setFormat:@"###.00"];
    

    for "55.23" and ".23" and ".20"

    [formatter setFormat:@"##0.00"];
    

    for "55.23" and "0.23" and "0.20"

    See Number Format String Syntax (Mac OS X Versions 10.0 to 10.3)

    Or you can use a 10.4 formatter with - setMinimumFractionDigits: and - setMaximumFractionDigits: with both set to 2.

    0 讨论(0)
  • 2020-12-31 16:16

    You might be better off with localizedStringWithFormat, like so...

    [UILabel alloc] initWithFrame:CGRectMake(80.0f, 90.0f, 225.0f, 40.0f)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    int bytes = 1024 * 1024;
    label.text = [NSString localizedStringWithFormat:@"0.00 MB of %.2f MB", ([self.totalFileSize floatValue] / bytes)];
    

    And of course, bytes could be a const unsigned, and clearColor tends to be a performance hog, but those are issues for another thread.

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