【问题标题】:Formatting float values in ios在 ios 中格式化浮点值
【发布时间】:2015-04-27 11:04:55
【问题描述】:

我有体重值,它们可以是 75 公斤和 75.5 公斤。

我希望这个值有两种样式: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;
}

【问题讨论】:

  • 你想要什么可以解释一下
  • 我希望这个值有两种样式:75kg、75.5kg,但不是 75.0kg。
  • 有没有任何格式化数字解决方案?
  • 你可以试试这个链接stackoverflow.com/questions/560517/…

标签: ios iphone numbers number-formatting


【解决方案1】:

最好的解决方案是使用数字格式化程序:

 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 不同的十进制数,它还可以帮助您使用设备上的当前语言环境选择正确的小数分隔符。

【讨论】:

    【解决方案2】:

    如果你不喜欢你的解决方案,那么看看我的解决方案

    float flotvalue = weightAtThePoint.floatValue;
    int reminder = flotvalue / 1.0;
    if (reminder==flotvalue) {
        NSLog(@"%f",flotvalue); //75KG Solution
    }
    else {
        //75.xx solution
    }
    

    享受编码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 2011-09-08
      • 2019-10-18
      • 1970-01-01
      • 2018-02-26
      相关资源
      最近更新 更多