Objective-c convert Long and float to String

后端 未结 3 1159
野的像风
野的像风 2020-12-30 20:55

I need to convert two numbers to string in Objective-C.

One is a long number and the other is a float.

I searched on the internet for a solution and everyone

相关标签:
3条回答
  • 2020-12-30 21:33

    floatValue has to be a double. At least this compiles correctly and does what is expected on my machine Floats can only store about 8 decimal digits and your number 12345678.1234 requires more precision than that, hence only about the 8 most significant digit are stored in a float.

    double floatValue = 12345678.1234;
    NSString *myString = [NSString stringWithFormat: @"%f", floatValue];
    

    results in

    2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400
    
    0 讨论(0)
  • 2020-12-30 21:47

    This article discusses how to use various formatting strings to convert numbers/objects into NSString instances:

    String Programming Guide: Formatting String Objects

    Which use the formats specified here:

    String Programming Guide: String Format Specifiers

    For your float, you'd want:

    [NSString stringWithFormat:@"%1.6f", floatValue]
    

    And for your long:

    [NSString stringWithFormat:@"%ld", longValue] // Use %lu for unsigned longs
    

    But honestly, it's sometimes easier to just use the NSNumber class:

    [[NSNumber numberWithFloat:floatValue] stringValue];
    [[NSNumber numberWithLong:longValue] stringValue];
    
    0 讨论(0)
  • 2020-12-30 21:54

    You should use NSNumberFormatter eg:

        NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
        [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
        [nFormatter release];
    
    0 讨论(0)
提交回复
热议问题