使用设备的货币设置格式化输出

时间:2011-06-06 08:32:45

标签: iphone cocoa-touch ios

我正在制作我的第一个iPhone应用程序,并希望能够使用设备的货币设置格式化货币。

目前我有这个:

- (IBAction)calculate {

    float lp = ([leftPrice.text floatValue]);
    float rp = ([rightPrice.text floatValue]);
    float lw = ([leftWeight.text floatValue]);
    float rw = ([rightWeight.text floatValue]);

    float lppkg = lp/lw;
    float rppkg = rp/rw;

    if (lp > 0 && lw > 0) {
        leftPricePerKg.text = [[NSString alloc] initWithFormat:@"$%.2f", lppkg];
    }

    if (rp > 0 && rw > 0) {
        rightPricePerKg.text = [[NSString alloc] initWithFormat:@"$%.2f", rppkg];
    }
}

1 个答案:

答案 0 :(得分:2)

您应该查看NSNumberFormatter -

你可以看看这里: https://developer.apple.com/documentation/foundation/numberformatter

在这里:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html#//apple_ref/doc/uid/TP40002368-SW1

特别是

“配置货币格式”部分

修改

我找到了 -

//--------------------------------------------
// Format style as currency, output to console
//--------------------------------------------
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
formattedOutput = [formatter stringFromNumber:[attributesDict objectForKey:NSFileSystemFreeSize]];
NSLog(@"Output as currency: %@", formattedOutput);

//--------------------------------------------
// Change local and output as currency
//--------------------------------------------
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"it_IT"];
[formatter setLocale:locale];
formattedOutput = [formatter stringFromNumber:[attributesDict objectForKey:NSFileSystemFreeSize]];
NSLog(@"Output as currency - locale it_IT: %@", formattedOutput);

下面: http://iosdevelopertips.com/cocoa/formatting-numbers-nsnumberformatter-examples.html