iphone - Round value iOS 中的浮点值

标签 iphone objective-c ios xcode nsnumber

我正在开发一个应用程序并且想要四舍五入值 即如果输出是 4.8 我想显示 4.8 而如果输出是 4.0 ,我想显示 4

此外,如果我可以精确地舍入值,那就太好了:如果值为 4.34,则舍入为 4.3,而如果值为 4.37,则舍入为 4.4

最佳答案

舍入浮点值的一种方法是仅添加 0.5,然后截断该值。

double valueToRound = GetTheValueFromSomewhere();
double roundedValue = (double)((int)(valueToRound + 0.5));

例如,这会将 1.4 舍入为 1.0,将 1.5 舍入为 2.0。要像您提到的那样四舍五入到其他小数位,只需将初始值乘以 10 或 100 等。使用相同类型的代码,然后将结果除以相同的数字,您将在任何小数点得到相同的结果你想要的地方。

这是一个以任意精度舍入的示例。

double valueToRound = GetTheValueFromSomewhere();
int decimalPrecisionAtWhichToRound = 0;
double scale = 10^decimalPrecisionAtWhichToRound;
double tmp = valueToRound * scale;
tmp = (double)((int)(tmp + 0.5));
double roundedValue = tmp / scale;

因此,如果像上面那样将 decimalPrecisionAtWhichToRound 设置为 0,它将舍入到最接近的整数。 1.4 将四舍五入为 1.0。 1.5 将四舍五入为 2.0。

如果将 decimalPrecisionAtWhichToRound 设置为 1,它将四舍五入到最接近的十分之一。 1.45 将四舍五入为 1.5,1.43 将四舍五入为 1.4。

关于iphone - Round value iOS 中的浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017270/

相关文章:

iphone - 为什么加载 View Controller 时没有调用我的 initWithNib 方法?

iphone - Xcode 中的约束问题

iphone - iCloud cocoa 错误512

objective-c - 为什么可变对象不需要双指针?

ios - 由于缺少 BluetoothDevice.h 文件,无法编译 BeeTee 框架

ios - UIGraphicsGetCurrentContext 没有出现在 UIView 中

ios - 在 SWIFT 中创建具有动态值/键的可变字典

ios - Alamofire 使凭证无效

objective-c - 在 UITextView 上用两根手指转发事件触摸

ios - Apple tvOS 中的视频下载