在Java中,我们使用$ currency格式来执行此语句.
double num1 = 3.99 ;
double num2 = 1.00 ;
double total = num1 + num2;
System.out.printf ("Total: $ %.2f", total);
Run Code Online (Sandbox Code Playgroud)
结果是:
总计:4.99美元
// --------------------------------
现在在iOS中,如果我有以下语句,我怎么能得到相同的格式:
total.text = [NSString stringWithFormat:@"$ %d",([self.coursePriceLabel.text intValue])+([self.courseEPPLabel.text intValue])+10];
Run Code Online (Sandbox Code Playgroud)
注意:
如果我使用doubleValue,则输出始终为0.
Cal*_*leb 10
你可以用NSString做同样的事情:
NSString *someString = [NSString stringWithFormat:@"$%.2lf", total];
Run Code Online (Sandbox Code Playgroud)
请注意,格式说明符是"%lf"而不仅仅是"%f".
但这只适用于美元.如果您想使代码更具可本地化,那么正确的做法是使用数字格式化程序:
NSNumber *someNumber = [NSNumber numberWithDouble:total];
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *someString = [nf stringFromNumber:someNumber];
Run Code Online (Sandbox Code Playgroud)
当然,用欧元符号或类似的东西显示以美元计算的值是不行的,因此您要么想要用用户的货币进行所有计算,要么在显示之前转换为用户的货币.您可能会发现NSValueTransformer对此有帮助.
| 归档时间: |
|
| 查看次数: |
6194 次 |
| 最近记录: |