iOS 将大数字转换为小格式 [英] iOS convert large numbers to smaller format

查看:45
本文介绍了iOS 将大数字转换为小格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将所有超过 3 位的数字转换为 4 位或更少的数字?

How can I convert all numbers that are more than 3 digits down to a 4 digit or less number?

这正是我的意思:

10345 = 10.3k
10012 = 10k
123546 = 123.5k
4384324 = 4.3m

四舍五入并不完全重要,而是一个额外的好处.

Rounding is not entirely important, but an added plus.

我已经研究过 NSNumberFormatter 但没有找到合适的解决方案,而且我还没有在 SO 上找到合适的解决方案.非常感谢任何帮助,谢谢!

I have looked into NSNumberFormatter but have not found the proper solution, and I have yet to find a proper solution here on SO. Any help is greatly appreciated, thanks!

推荐答案

以下是我想出的两种方法,它们可以共同产生预期的效果.这也将自动四舍五入.这还将通过传递 int dec 指定总共有多少数字可见.

Here are two methods I have come up with that work together to produce the desired effect. This will also automatically round up. This will also specify how many numbers total will be visible by passing the int dec.

另外,在float to string方法中,可以将@"%.1f"改为@"%.2f", @"%.3f" 等告诉它小数点后显示多少可见小数.

Also, in the float to string method, you can change the @"%.1f" to @"%.2f", @"%.3f", etc to tell it how many visible decimals to show after the decimal point.

For Example:

52935 --->  53K
52724 --->  53.7K





-(NSString *)abbreviateNumber:(int)num withDecimal:(int)dec {

    NSString *abbrevNum;
    float number = (float)num;

    NSArray *abbrev = @[@"K", @"M", @"B"];

    for (int i = abbrev.count - 1; i >= 0; i--) {

        // Convert array index to "1000", "1000000", etc
        int size = pow(10,(i+1)*3);

        if(size <= number) {
            // Here, we multiply by decPlaces, round, and then divide by decPlaces.
            // This gives us nice rounding to a particular decimal place.
            number = round(number*dec/size)/dec;

            NSString *numberString = [self floatToString:number];

            // Add the letter for the abbreviation
            abbrevNum = [NSString stringWithFormat:@"%@%@", numberString, [abbrev objectAtIndex:i]];

            NSLog(@"%@", abbrevNum);

        }

    }


    return abbrevNum;
}

- (NSString *) floatToString:(float) val {

    NSString *ret = [NSString stringWithFormat:@"%.1f", val];
    unichar c = [ret characterAtIndex:[ret length] - 1];

    while (c == 48 || c == 46) { // 0 or .
        ret = [ret substringToIndex:[ret length] - 1];
        c = [ret characterAtIndex:[ret length] - 1];
    }

    return ret;
}

希望这可以帮助其他需要它的人!

Hope this helps anyone else out who needs it!

这篇关于iOS 将大数字转换为小格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆