我在浮点数中有值25.00,但当我在屏幕上打印它时,它是25.0000000。 如何显示只有两位小数点后的值?


当前回答

如果你也需要浮动值:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);

其他回答

如果你也需要浮动值:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);

使用NSNumberFormatter和maximumFractionDigits,如下所示:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);

你会得到12.35

下面是一些根据精度动态格式化的方法:

+ (NSNumber *)numberFromString:(NSString *)string
{
    if (string.length) {
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        f.numberStyle = NSNumberFormatterDecimalStyle;
        return [f numberFromString:string];
    } else {
        return nil;
    }
}

+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
    NSNumber *numberValue = [self numberFromString:string];

    if (numberValue) {
        NSString *formatString = [NSString stringWithFormat:@"%%.%ldf", (long)precision];
        return [NSString stringWithFormat:formatString, numberValue.floatValue];
    } else {
        /* return original string */
        return string;
    }
}

如。

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];

=> 2.3453

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];

=> 2

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];

=> 2.35(取整)

Swift的另一个方法(不使用NSString):

let percentage = 33.3333
let text = String.localizedStringWithFormat("%.02f %@", percentage, "%")

附注:此解决方案不适用于CGFloat类型,仅用Float & Double测试

 lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];