简体   繁体   English

在iOS中格式化浮点值

[英]Formatting float values in ios

I have weight values, they can be like 75kg and 75.5kg. 我有体重值,可以是75kg和75.5kg。

I want to have this values two styles: 75kg, 75.5kg, but NOT 75.0kg. 我希望此值具有两种样式:75kg,75.5kg,但不是75.0kg。 How can I do it? 我该怎么做?

I have this solution, but I not like it 我有此解决方案,但我不喜欢

//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;
}

If you don't like your solution, then take look at my solution 如果您不喜欢自己的解决方案,请查看我的解决方案

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

Enjoy Coding 享受编码

The best solution would be using a number formatter: 最好的解决方案是使用数字格式化程序:

 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]];
    });

Since the number formatter creation requires some resources is better if you create a single instance. 由于创建数字格式化程序需要一些资源,因此,如果您创建一个实例,则更好。
When you need to print a string just call this: 当您需要打印字符串时,只需调用以下命令:

NSString * formattedString = [numberformatter stringFromNumber: weightAtThePoint];<br>

NSNumberFomatter prints only the decimal number if it is different from 0 and it also helps you in choosing the correct decimal separator by using the current locale on the device. NSNumberFomatter 0,则仅输出十进制数字,它还可以帮助您使用设备上的当前语言环境选择正确的十进制分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM