簡體   English   中英

Objective-c將Long和float轉換為String

[英]Objective-c convert Long and float to String

我需要在Objective-C中將兩個數字轉換為字符串。

一個是長號,另一個是浮點數。

我在互聯網上搜索了一個解決方案,每個人都使用stringWithFormat:但我不能讓它工作。

我試試

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

對於12345678.1234並獲得“12345678.00000”作為輸出

NSString *myString = [NSString stringWithFormat: @"%d", longValue]

有人可以告訴我如何正確使用stringWithFormat:

本文討論如何使用各種格式字符串將數字/對象轉換為NSString實例:

字符串編程指南:格式化字符串對象

哪個使用此處指定的格式:

字符串編程指南:字符串格式說明符

對於你的浮動,你需要:

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

而且你的長期:

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

但老實說,有時使用NSNumber類更容易:

[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];

floatValue必須是double。 至少這個正確編譯並完成我的機器上的預期Floats只能存儲大約8個十進制數字,而你的數字12345678.1234需要更高的精度,因此只有大約8個最高有效數字存儲在一個浮點數中。

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

結果是

2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400

您應該使用NSNumberFormatter,例如:

    NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
    [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
    [nFormatter release];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM