是否有用于使用 SI 单位进行计算的 IOS 框架



我正在将质量(如g,mg,μg,ng&kg)和体积(如ml,μl和l)作为化学应用程序的输入。

目前,我将所有质量转换为克,将体积转换为升,保存在核心数据中,并以双倍形式执行任何计算。

最后,结果被转换回有意义的单位即 0.000034 升对我的客户更有用,表示为 34μl

在不同单位之间工作的最佳实践是什么?

可能有一些

库,但你正在做的事情是具体的,所以我怀疑是否有特定的"最佳实践"。

你可能想研究 NSDouble 的属性,CGFloat但是因为它们可能更适合跨设备,并为您提供更多选择,它们是原始的替身。

没有单位数据类型或许多内置本机转换器函数。数字是一个数字,由程序员在应用程序的上下文中赋予该数字含义。

我在 https://github.com/dhoerl/EngineeringNotationFormatter 找到了合适的工程格式化程序

此外,我还创建了一个简单的版本:

-(NSString *)engineeringFormat:(double)value digits:(int)digits {
//calculate exponent in step of 3
int perMill = trunc(log10(value)/3);
if (value<1) {
    perMill -= 1;
}
//calculate mantissa format range of 1 to 1000
double corrected = value;
while (corrected<1) {
    corrected = corrected*1000;
        }
while (corrected>=1000) {
    corrected=corrected/1000;
}
//format number of significant digits
NSNumberFormatter *numberFormatDigits = [[NSNumberFormatter alloc] init];
numberFormatDigits.usesSignificantDigits = YES;
numberFormatDigits.maximumSignificantDigits = digits;
NSString *mantissa = [numberFormatDigits stringFromNumber:[NSNumber numberWithDouble:corrected]];
//select engineering notation prefix
NSArray *engSuffix = @[@"T",@"G",@"M",@"k",@"",@"m",@"µ",@"n",@"p"];
int index = 4 - perMill;
NSString *result;
if ((index > engSuffix.count-1) || (index<0)) {
    result = @"Out of range";
} else {
    result = [NSString stringWithFormat:@"%@ %@",mantissa,[engSuffix objectAtIndex:index]];
}
return result;

}

最新更新