How do I delete trailing zeros on floats without rounding in Objective-C?

前端 未结 2 1035
北恋
北恋 2021-01-31 21:11

I need to clear trailing zeros on floats without rounding? I need to only display relevant decimal places.

For example, if I have 0.5, I need it to show 0.5, not 0.5000

相关标签:
2条回答
  • 2021-01-31 21:26

    Use the following:

    NSString* floatString = [NSString stringWithFormat:@"%g", myFloat];
    
    0 讨论(0)
  • 2021-01-31 21:41

    NSNumberFormatter is the way to go:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    formatter.maximumFractionDigits = 20;
    
    NSString *result = [formatter stringFromNumber:@1.20];
    NSLog(@"%@", result);
    
    result = [formatter stringFromNumber:@0.00031];
    NSLog(@"%@", result);
    

    This will print:

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