oc 数值转换

简介:

Objective-C拓展了C,自然很多用法是和C一致的。比如浮点数转化成整数,就有以下四种情况。 
1.简单粗暴,直接转化

float f = 1.5; int a; a = (int)f; NSLog("a = %d",a);

输出结果是1。(int)是强制类型转化,丢弃浮点数的小数部分。

2.高斯函数,向下取整

float f = 1.6; int a; a = floor(f); NSLog("a = %d",a);

输出结果是1。floor()方法是向下取整,类似于数学中的高斯函数 [].取得不大于浮点数的最大整数,对于正数来说是舍弃浮点数部分,对于复数来说,舍弃浮点数部分后再减1.

3.ceil函数,向上取整。

float f = 1.5; int a; a = ceil(f); NSLog("a = %d",a);

输出结果是2。ceil()方法是向上取整,取得不小于浮点数的最小整数,对于正数来说是舍弃浮点数部分并加1,对于复数来说就是舍弃浮点数部分.

4.通过强制类型转换四舍五入。

float f = 1.5; int a; a = (int)(f+0.5); NSLog("a = %d",a);

其中原理非常简单,所以就不做详细说明了。

在iOS开发中,和货币价格计算相关的,需要注意计算精度的问题。即使只是两位小数,也会出现误差。使用float类型运算,是完全不够的。经过一番测试,最后选择使用系统提供的API的NSDecimalNumber来进行更好的解决。

作为一个对外的库,鉴于版本延续,我们保留对外的flaot的类型,不改变接口,选择进行内部适配。

以下是一些基本的测试,

原始数据

float a = 0.01;

int b = 99999999;

double c = 0.0;

1:使用浮点运算,

c = a*b;

NSLog(@"%f",c);

NSLog(@"%.2f",c);

使用double类型存储没有触及问题的实质,完全不能解决。

2011-12-30 11:04:00.121 Untitled[2912:207] 1000000.000000

2011-12-30 11:04:00.123 Untitled[2912:207] 1000000.00

 

2:使用类型转换,提高精度

c = a*(double)b;

NSLog(@"%f",c);

NSLog(@"%.2f",c);

Double运算的精度是提高了,可是浮点数的数值早已经出现了精度的不准确,即使存储空间足够,同样还是不准确的数值。

2011-12-30 11:04:00.123 Untitled[2912:207] 999999.967648

2011-12-30 11:04:00.124 Untitled[2912:207] 999999.97

 

3:通过和NSString的转换,将计算的原始数据转换为纯粹的double类型的数据,这样的计算精度就可以达到要求了。

NSString *objA = [NSString stringWithFormat:@"%.2f", a];

NSString *objB = [NSString stringWithFormat:@"%.2f", (double)b];

c = [objA doubleValue] * [objB doubleValue];

NSLog(@"%.2f",c);

计算的结果还是比较准确的,不过需要做格式化输入和格式化输出的处理。同时使用NSString来转换,这样的写法看起来比较奇怪。

2011-12-30 11:04:00.190 Untitled[2912:207] 999999.99

 

4:个人还是比较喜欢使用系统提供的类型来进行计算。通过NSDecimalNumber提供的计算方式,可以很好的计算出准确的精度的数据,同时不需要使用格式化输出等。

其计算的精度是比较高,这是官方建议的货币计算的API,对乘除等计算都有单独的API接口来提供。

NSString *decimalNumberMutiplyWithString(NSString *multiplierValue,NSString *multiplicandValue)

{

     NSDecimalNumber *multiplierNumber = [NSDecimalNumber decimalNumberWithString:multiplierValue];

     NSDecimalNumber *multiplicandNumber = [NSDecimalNumber decimalNumberWithString:multiplicandValue];

     NSDecimalNumber *product = [multiplicandNumber decimalNumberByMultiplyingBy:multiplierNumber];

     return [product stringValue];

}

 

NSLog(@"%@",decimalNumberMutiplyWithString([NSString stringWithFormat:@"%f",a], [NSString stringWithFormat:@"%d",b]));

 

2011-12-30 11:04:00.251 Untitled[2912:207] 999999.99

 

只是测试,所以接口名大致写写,名字取得比较不那么讲究,希望可以表达清楚。

 

总的来说,对于货币计算,应该需要注意精度的问题。同时在运算的时候,应该优先选用框架提供的API,否则,就应该使用足够精度的类型运算,同时对自己写的接口进行足够的说明,要求开发者按照规范来使用。

在自己不能保证足够准确的情况下,用适当的说明的要求来规避责任还是可以接受的。至少被人抱怨两句总比出错强。


elf.orderCost.text = [NSStringstringWithFormat:@"%.1f",self.order.cost.floatValue];

%.1f  表示小数点一位,%.2f 表示小数点2位,依次类推.




格式定义
The format specifiers supported by the NSString formatting methods and CFString formatting functions follow the IEEE printf specification; the specifiers are summarized in Table 1. Note that you can also use the “n$” positional specifiers such as %1$@ %2$s. For more details, see the IEEE printf specification. You can also use these format specifiers with the NSLog function.

Table 1 Format specifiers supported by the NSString formatting methods and CFString formatting functions 定义 说明 %@ Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function. %% ‘%’ character %d, %D, %i Signed 32-bit integer (int) %u, %U Unsigned 32-bit integer (unsigned int) %hi Signed 16-bit integer (short) %hu Unsigned 16-bit integer (unsigned short) %qi Signed 64-bit integer (long long) %qu Unsigned 64-bit integer (unsigned long long) %x Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and lowercase a–f %X Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F %qx Unsigned 64-bit integer (unsigned long long), printed in hexadecimal using the digits 0–9 and lowercase a–f %qX Unsigned 64-bit integer (unsigned long long), printed in hexadecimal using the digits 0–9 and uppercase A–F %o, %O Unsigned 32-bit integer (unsigned int), printed in octal %f 64-bit floating-point number (double) %e 64-bit floating-point number (double), printed in scientific notation using a lowercase e to introduce the exponent %E 64-bit floating-point number (double), printed in scientific notation using an uppercase E to introduce the exponent %g 64-bit floating-point number (double), printed in the style of %e if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise %G 64-bit floating-point number (double), printed in the style of %E if the exponent is less than –4 or greater than or equal to the precision, in the style of %f otherwise %c 8-bit unsigned character (unsigned char), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit %C 16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format \\ddd or the Unicode hexadecimal format \\udddd, where d is a digit %s Null-terminated array of 8-bit unsigned characters. %s interprets its input in the system encoding rather than, for example, UTF-8. %S Null-terminated array of 16-bit Unicode characters %p Void pointer (void *), printed in hexadecimal with the digits 0–9 and lowercase a–f, with a leading 0x %L Length modifier specifying that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument %a 64-bit floating-point number (double), printed in scientific notation with a leading 0x and one hexadecimal digit before the decimal point using a lowercase p to introduce the exponent %A 64-bit floating-point number (double), printed in scientific notation with a leading 0X and one hexadecimal digit before the decimal point using a uppercase P to introduce the exponent %F 64-bit floating-point number (double), printed in decimal notation %z Length modifier specifying that a following d, i, o, u, x, or X conversion specifier applies to a size_t or the corresponding signed integer type argument %t Length modifier specifying that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument %j Length modifier specifying that a following d, i, o, u, x, or X conversion specifier applies to a intmax_t or uintmax_t argument

平台依赖
Mac OS X uses several data types—NSInteger, NSUInteger,CGFloat, and CFIndex—to provide a consistent means of representing values in 32- and 64-bit environments. In a 32-bit environment, NSInteger and NSUInteger are defined as int and unsigned int, respectively. In 64-bit environments, NSInteger and NSUInteger are defined as long and unsigned long, respectively. To avoid the need to use different printf-style type specifiers depending on the platform, you can use the specifiers shown in Table 2. Note that in some cases you may have to cast the value.

Table 2 Format specifiers for data types 类型 定义 建议 NSInteger %ld or %lx Cast the value to long NSUInteger %lu or %lx Cast the value to unsigned long CGFloat %f or %g %f works for floats and doubles when formatting; but see below warning when scanning CFIndex %ld or %lx The same as NSInteger pointer %p %p adds 0x to the beginning of the output. If you don’t want that, use %lx and cast to long. long long %lld or %llx long long is 64-bit on both 32- and 64-bit platforms unsigned long long %llu or %llx unsigned long long is 64-bit on both 32- and 64-bit platforms

The following example illustrates the use of %ld to format an NSInteger and the use of a cast.

1
2

NSInteger i = 42;
printf("%ld\n"(long)i);

In addition to the considerations mentioned in Table 2, there is one extra case with scanning: you must distinguish the types for float and double. You should use %f for float, %lf for double. If you need to use scanf (or a variant thereof) with CGFloat, switch to double instead, and copy the double to CGFloat.

1
2
3
4

CGFloat imageWidth;
double tmp;
sscanf (str, "%lf"&tmp);
imageWidth = tmp;

It is important to remember that %lf does not represent CGFloat correctly on either 32- or 64-bit platforms. This is unlike %ld, which works for long in all cases.











本文转自ljianbing51CTO博客,原文链接:http://blog.51cto.com/ljianbing/1758276  ,如需转载请自行联系原作者

相关文章
|
安全 数据安全/隐私保护 iOS开发
flutter 代码混淆
flutter 代码混淆
400 0
|
Android开发 iOS开发 MacOS
APP备案公钥、证书MD5指纹/签名MD5值获取最简单方法
APP备案公钥、证书MD5指纹/签名MD5值获取方法,Android安卓平台、Windows平台、macOS平台,三个平台获取方法, Android平台使用 APP备案助手,各大安卓应用市场搜索 APP备案助手 即可,Windows/macOS平台使用jadx-gui工具。
7946 3
|
缓存 数据安全/隐私保护 iOS开发
2023最新mac开启ntfs读写功能 ntfs硬盘如何在mac上读写教程
在日常的工作中,总是避免不了跨平台的传输文件、文件共享等,例如一些用户使用Mac电脑修图或者剪辑视频之后需要拷贝到Windows电脑上查看。对于需要同时使用Mac和Windows的用户来说,系统之间不兼容是很大的阻碍,尤其是使用NTFS移动硬盘,用户会遇到Mac电脑无法写入NTFS硬盘的情况,本文就来教大家ntfs硬盘如何在mac上读写以及mac如何移动硬盘的文件。
4625 0
2023最新mac开启ntfs读写功能 ntfs硬盘如何在mac上读写教程
|
JavaScript 前端开发
Element-ui 中表单(Form)验证数字值范围(大小)
Element-ui 中表单(Form)验证数字值范围(大小)
2596 0
Element-ui 中表单(Form)验证数字值范围(大小)
|
JavaScript
|
开发工具 git 缓存
Git忽略规则.gitignore不生效
在项目开发过程中个,一般都会添加 .gitignore 文件,规则很简单,但有时会发现,规则不生效。 原因是 .gitignore 只能忽略那些原来没有被track的文件,如果某些文件已经被纳入了版本管理中,则修改.gitignore是无效的。
61914 4
|
6月前
|
数据采集 存储 数据可视化
2025python实战:利用海外代理IP验证广告投放效果
本文介绍了如何利用Python结合海外代理IP技术,验证广告在不同国家的实际投放效果。通过模拟各地网络环境访问广告页面,检查内容是否与计划一致,并生成曝光报告。具体实现包括:获取高质量代理IP、使用Selenium或Playwright模拟用户行为、解析广告内容及生成可视化报告。案例显示,该方法能有效确保广告精准投放,优化策略并节省预算。
|
9月前
|
存储 安全 虚拟化
Windows 11 绕过 TPM 方法总结,通用免 TPM 镜像下载 (2025 年 2 月更新)
Windows 11 绕过 TPM 方法总结,通用免 TPM 镜像下载 (2025 年 2 月更新)
450 0
Windows 11 绕过 TPM 方法总结,通用免 TPM 镜像下载 (2025 年 2 月更新)
|
人工智能 算法 大数据
懂场景者得AI,瓴羊发布年度产品智能化战略
9月20日,瓴羊智能科技(以下简称瓴羊)在2024云栖大会上举办了“Data × AI:企业服务智能化,价值增长新动能”专场论坛。阿里巴巴集团副总裁、瓴羊智能科技CEO 朋新宇在会上发布年度产品智能化战略:“(算法 + 算力 + 数据) x 场景 ”,强调企业必须重视场景,只有通过解构场景、重构业务,才能真正拥抱AI,带来突破性增长。
318 14
|
存储 Cloud Native Shell
go库介绍:Golang中的Viper库
Viper 是 Golang 中的一个强大配置管理库,支持环境变量、命令行参数、远程配置等多种配置来源。本文详细介绍了 Viper 的核心特点、应用场景及使用方法,并通过示例展示了其强大功能。无论是简单的 CLI 工具还是复杂的分布式系统,Viper 都能提供优雅的配置管理方案。
335 6