formatting - iOS convert large numbers to smaller format -
how can convert numbers more 3 digits down 4 digit or less number?
this mean:
10345 = 10.3k 10012 = 10k 123546 = 123.5k 4384324 = 4.3m
rounding not entirely important, added plus.
i have looked nsnumberformatter have not found proper solution, , have yet find proper solution here on so. appreciated, thanks!
-(nsstring*) suffixnumber:(nsnumber*)number { if (!number) return @""; long long num = [number longlongvalue]; int s = ( (num < 0) ? -1 : (num > 0) ? 1 : 0 ); nsstring* sign = (s == -1 ? @"-" : @"" ); num = llabs(num); if (num < 1000) return [nsstring stringwithformat:@"%@%lld",sign,num]; int exp = (int) (log10l(num) / 3.f); //log10l(1000)); nsarray* units = @[@"k",@"m",@"g",@"t",@"p",@"e"]; return [nsstring stringwithformat:@"%@%.1f%@",sign, (num / pow(1000, exp)), [units objectatindex:(exp-1)]]; }
sample usage
nslog(@"%@",[self suffixnumber:@100]); // 100 nslog(@"%@",[self suffixnumber:@1000]); // 1.0k nslog(@"%@",[self suffixnumber:@1500]); // 1.5k nslog(@"%@",[self suffixnumber:@24000]); // 24.0k nslog(@"%@",[self suffixnumber:@99900]); // 99.9k nslog(@"%@",[self suffixnumber:@99999]); // 100.0k nslog(@"%@",[self suffixnumber:@109999]); // 110.0k nslog(@"%@",[self suffixnumber:@5109999]); // 5.1m nslog(@"%@",[self suffixnumber:@8465445223]); // 8.5g nslog(@"%@",[self suffixnumber:[nsnumber numberwithint:-120]]); // -120 nslog(@"%@",[self suffixnumber:[nsnumber numberwithlong:-5000000]]); // -5.0m nslog(@"%@",[self suffixnumber:[nsnumber numberwithdouble:-3.5f]]); // -3 nslog(@"%@",[self suffixnumber:[nsnumber numberwithdouble:-4000.63f]]); // -4.0k
[update]
swift version below:
func suffixnumber(number:nsnumber) -> nsstring { var num:double = number.doublevalue; let sign = ((num < 0) ? "-" : "" ); num = fabs(num); if (num < 1000.0){ return "\(sign)\(num)"; } let exp:int = int(log10(num) / 3.0 ); //log10(1000)); let units:[string] = ["k","m","g","t","p","e"]; let roundednum:double = round(10 * num / pow(1000.0,double(exp))) / 10; return "\(sign)\(roundednum)\(units[exp-1])"; }
sample usage
print(self.suffixnumber(nsnumber(long: 100))); // 100.0 print(self.suffixnumber(nsnumber(long: 1000))); // 1.0k print(self.suffixnumber(nsnumber(long: 1500))); // 1.5k print(self.suffixnumber(nsnumber(long: 24000))); // 24.0k print(self.suffixnumber(nsnumber(longlong: 99900))); // 99.9k print(self.suffixnumber(nsnumber(longlong: 99999))); // 100.0k print(self.suffixnumber(nsnumber(longlong: 109999))); // 110.0k print(self.suffixnumber(nsnumber(longlong: 5109999))); // 5.1k print(self.suffixnumber(nsnumber(longlong: 8465445223))); // 8.5g print(self.suffixnumber(nsnumber(long: -120))); // -120.0 print(self.suffixnumber(nsnumber(longlong: -5000000))); // -5.0m print(self.suffixnumber(nsnumber(float: -3.5))); // -3.5 print(self.suffixnumber(nsnumber(float: -4000.63))); // -4.0k
hope helps
Comments
Post a Comment