ios - 从值中获取数字的最短方法

标签 ios objective-c numbers int digits

假设我有一个像 134658 这样的数字,我想要第 3 个数字(百位),即“6”。

在Objective-C中得到它的最短长度代码是多少?

这是我当前的代码:

int theNumber = 204398234;
int theDigitPlace = 3;//hundreds place
int theDigit = (int)floorf((float)((10)*((((float)theNumber)/(pow(10, theDigitPlace)))-(floorf(((float)theNumber)/(pow(10, theDigitPlace)))))));

//Returns "2"

最佳答案

可能有更好的解决方案,但这个稍微短一些:

int theNumber = 204398234;
int theDigitPlace = 3;//hundreds place
int theDigit = (theNumber/(int)(pow(10, theDigitPlace - 1))) % 10;

在您的情况下,它将数字除以 100 得到 2043982,然后“提取” 带有“余数运算符”% 的最后一位十进制数字。

备注:该解决方案假设 pow(10, theDigitPlace - 1) 的结果是 精确的。这是有效的,因为 double 在 iOS 上有大约 16 位有效的十进制数字和 int 是一个 32 位数字,最多有 10 位小数。

关于ios - 从值中获取数字的最短方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23205384/

相关文章:

ios - 是否可以在 UIProgressView 中添加多种颜色?

python - 在python中生成1到6之间的6个随机数列表

c# - 在 .NET 中将 int 的数字分隔成数组的最快方法?

javascript - 找出能被 3 整除的 3 个数的最大和

ios - CloudKit 在不同的 iCloud 帐户之间共享数据,但不是与所有人共享

iOS 应用程序在下载非常大的文件时耗尽内存

ios - Nativescript 5 - 无法使用 xcode 进行分析

iOS:未使用重用标识符清除单元格内容

iphone - 良好的模型设计策略

objective-c - WebView 中的后退/前进滑动手势