iOS Convert Large Numbers to Smaller Format

iOS convert large numbers to smaller format

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.

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!

How to format the number in ios

You have to do it by hand like this:

func format(number: Double) -> String {

let sign = ((number < 0) ? "-" : "" )
let num = fabs(number)

// If its only three digit:
if (num < 1000.0){
return String(format:"\(sign)%g", num)
}

// Otherwise
let exp: Int = Int(log10(num)/3.0)
let units: [String] = ["K","M","B","T","P","E"]

let roundedNum: Double = round(10 * num / pow(1000.0,Double(exp))) / 10

return String(format:"\(sign)%g\(units[exp-1])", roundedNum)
}

print(format(number: 999)) // Prints 999
print(format(number: 1000)) // Prints 1K
print(format(number: 290000)) // Prints 290K
print(format(number: 290200)) // Prints 290.2K
print(format(number: 3456200)) // Prints 3.5M

Source: iOS convert large numbers to smaller format

Swift: Formatting currencies with localized million and billion text

You will have to implement your own solution, but it is not hard. One way to go would be to create two dictionaries where the key will be the Locale identifier and the value the translation:

let millionTrans = [ "en_US" : "million", ...]
let billionTrans = [ "en_US': "billion", ...]

then get the Locale.current, find out if the amount is in the millions or billions and query the appropriate dictionary to get its value.

Swift 4: Formatting number's into friendly K's

This answer formats by truncating (versus rounding). 1,515 rounded would generate 2k whereas truncated would generate 1.5k. The function requires reducing a number's scale (removing digits to the right of the decimal) which I've just packaged as an extension so it can be used anywhere (not just in the function).

extension Double {
func reduceScale(to places: Int) -> Double {
let multiplier = pow(10, Double(places))
let newDecimal = multiplier * self // move the decimal right
let truncated = Double(Int(newDecimal)) // drop the fraction
let originalDecimal = truncated / multiplier // move the decimal back
return originalDecimal
}
}

func formatNumber(_ n: Int) -> String {
let num = abs(Double(n))
let sign = (n < 0) ? "-" : ""

switch num {
case 1_000_000_000...:
var formatted = num / 1_000_000_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)B"

case 1_000_000...:
var formatted = num / 1_000_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)M"

case 1_000...:
var formatted = num / 1_000
formatted = formatted.reduceScale(to: 1)
return "\(sign)\(formatted)K"

case 0...:
return "\(n)"

default:
return "\(sign)\(n)"
}
}

You can fine tune this method for specific cases, such as returning 100k instead of 100.5k or 1M instead of 1.1M. This method handles negatives as well.

print(formatNumber(1515)) // 1.5K
print(formatNumber(999999)) // 999.9K
print(formatNumber(1000999)) // 1.0M

iOS: Convert Integer with value over Thousand to a shorter Integer with letter 'K'

NSString *intWithK = myint >= 1000 ? [NSString stringWithFormat:@"%dk", myint / 1000] : [NSString stringWithFormat:@"%d", myint]

Should work :)

I your integer (I called it myint) is greater or equal to 1000 it'll divide it by 1000 and add "k", but won't do anything if it's smaller

NSNumberFormatter : Show 'k' instead of ',000' in large numbers?

edit/update

Swift 3 or later

extension FloatingPoint {
var kFormatted: String {
return String(format: self >= 1000 ? "$%.0fK" : "$%.0f", (self >= 1000 ? self/1000 : self) as! CVarArg )
}
}

The you can use it like this to format your output:

10.0.kFormatted     // "$10"
100.0.kFormatted // "$100"
1000.0.kFormatted // "$1K"
10000.0.kFormatted // "$10K"
162000.0.kFormatted // "$162K"
153000.0.kFormatted // "$153K"
144000.0.kFormatted // "$144K"
135000.0.kFormatted // "$135K"
126000.0.kFormatted // "$126K"

Converting very large NSDecimal to string eg. 400,000,000,000 - 400 T and so forth

Solved my issue: Can only be used if you know that your NSDecimal that you are trying to format will only be a whole number without decimals so make sure you round when doing any math on the NSDecimals.

-(NSString *)returnFormattedString:(NSDecimal)nsDecimalToFormat{

NSMutableArray *formatArray = [NSMutableArray arrayWithObjects:@"%.2f",@"%.1f",@"%.0f",nil];

NSMutableArray *suffixes = [NSMutableArray arrayWithObjects:@"k",@"M",@"B",@"T",@"Qa",@"Qi",@"Sx",@"Sp",@"Oc",@"No",@"De",@"Ud",@"Dud",@"Tde",@"Qde",@"Qid",@"Sxd",@"Spd",@"Ocd",@"Nvd",@"Vi",@"Uvi",@"Dvi",@"Tvi", nil];

int dick = [suffixes count];

NSLog(@"count %i",dick);

NSString *string = NSDecimalString(&nsDecimalToFormat, _usLocale);
NSString *formatedString;
NSUInteger characterCount = [string length];
if (characterCount > 3) {

NSString *trimmedString=[string substringToIndex:3];

float a;

a = 100.00/(pow(10, (characterCount - 4)%3));
int remainder = (characterCount-4)%3;

int suffixIndex = (characterCount + 3 - 1)/3 - 2;
NSLog(@"%i",suffixIndex);
if(suffixIndex < [suffixes count]){
NSString *formatSpecifier = [formatArray[remainder] stringByAppendingString:suffixes[suffixIndex]];
formatedString= [NSString stringWithFormat:formatSpecifier, [trimmedString floatValue] / a];

}
else {
formatedString = @"too Big";
}

}
else{
formatedString = string;
}

return formatedString;

}

Swift how to format a large number with thousands separators?

Swift Xcode 6.3, SOLVED (I decided to leave the $ in the code). If you don't want a $ in the output, change .CurrencyStyle to .DecimalStyle

var fv = 3534234.55 
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0;
resultFV.text = formatter.stringFromNumber(fv) // result: $3,534,235 –

NSNumberFormatter set multiplier for dividing with large number

Looks like you're exceeding the minimum value allowed for the multiplier. I can't find docs on it, but quick testing shows:

[numberFormatter setMultiplier: @(1.0 / 8388608.0)];

works fine, but

[numberFormatter setMultiplier: @(1.0 / 8388609.0)];

fails (string output is always "0").

So I don't think NSNumberFormatter is going to fit your needs.

Converting Int to Float loses precision for large numbers in Swift

This is due to the way the floating-point format works. A Float is a 32-bit floating-point number, stored in the IEEE 754 format, which is basically scientific notation, with some bits allocated to the value, and some to the exponent (in base 2), as this diagram from the single-precision floating-point number Wikipedia article shows:

32-bit float format

So the actual number is represented as

(sign) * (value) * (2 ^ (exponent))

Because the number of bits allocated to actually storing an integer value (24) is smaller than the number of bits allocated for this in a normal integer (all 32), in order to make room for the exponent, the less significant digits of large numbers will be sacrificed, in exchange for the ability to represent almost infinite numbers (a normal Int can only represent integers in the range -2^31 to 2^31 - 1).

Some rough testing indicates that every integer up to and including 16777216 (2 ^ 24) can be represented exactly in a 32-bit float, while larger integers will be rounded to the nearest multiple of some power of 2.

Note that this isn't specific to Swift. This floating-point format is a standard format used in almost every programming language. Here's the output I get from LLDB with plain C:

Sample Image

If you need higher precision, use a Double. Double precision floats use 64 bits of memory, and have higher precision.



Related Topics



Leave a reply



Submit