OGeek|极客世界-中国程序员成长平台

标题: iphone - 四舍五入大整数-objective-c [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:46
标题: iphone - 四舍五入大整数-objective-c

我如何在 Objective-c 中实现以下目标?

从 0 到 999,999,999 之间的整数 x 开始。 并以整数 y 结尾。

如果 x 介于 0 和 9999 之间,则 y = x 否则,x 会变成 45k(代表 45,000)或 998m(代表 9.98 亿)。换句话说,使用字符“k”和“m”以保持 y 小于或等于 4 个字符的长度。



Best Answer-推荐答案


不圆而简单地切断:

NSString *text;
if (x >= 1000000) text = [NSString stringWithFormat"%dm",x/1000000];
else if (x >= 1000) text = [NSString stringWithFormat"%dk",x/1000];
else text = [NSString stringWithFormat"%d",x];

舍入解:

NSString *text;
if (x >= 1000000) text = [NSString stringWithFormat"%.0fm",x/1000000.0f];
else if (x >= 1000) text = [NSString stringWithFormat"%.0fk",x/1000.0f];
else text = [NSString stringWithFormat"%d",x];

如果您想要更高的精度,请使用 float%.1f 等。

关于iphone - 四舍五入大整数-objective-c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709015/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4