[英]Formatting float values in ios
我有體重值,可以是75kg和75.5kg。
我希望此值具有兩種樣式:75kg,75.5kg,但不是75.0kg。 我該怎么做?
我有此解決方案,但我不喜歡
//show difference in 75 and 75.5 values style
NSString *floatWeight = [NSString stringWithFormat:@"%.1f",weightAtThePoint.floatValue];
NSString *intWeight = [NSString stringWithFormat:@"%.0f.0",weightAtThePoint.floatValue];
NSString *resultWeight;
if ([floatWeight isEqualToString:intWeight]) {
resultWeight = [NSString stringWithFormat:@"%.0f",weightAtThePoint.floatValue];
} else {
resultWeight = floatWeight;
}
如果您不喜歡自己的解決方案,請查看我的解決方案
float flotvalue = weightAtThePoint.floatValue;
int reminder = flotvalue / 1.0;
if (reminder==flotvalue) {
NSLog(@"%f",flotvalue); //75KG Solution
}
else {
//75.xx solution
}
享受編碼
最好的解決方案是使用數字格式化程序:
static NSNumberFormatter * numberformatter = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
numberformatter = [[NSNumberFormatter alloc] init];
[numberformatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberformatter setMaximumFractionDigits:1];
[numberformatter setMinimumFractionDigits:0];
[numberformatter setLocale:[NSLocale currentLocale]];
});
由於創建數字格式化程序需要一些資源,因此,如果您創建一個實例,則更好。
當您需要打印字符串時,只需調用以下命令:
NSString * formattedString = [numberformatter stringFromNumber: weightAtThePoint];<br>
NSNumberFomatter
0,則僅輸出十進制數字,它還可以幫助您使用設備上的當前語言環境選擇正確的十進制分隔符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.