Format Number Like Stack Overflow (Rounded to Thousands with K Suffix)

Format Number like Stack Overflow (rounded to thousands with K suffix)

Like this: (EDIT: Tested)

static string FormatNumber(int num) {
if (num >= 100000)
return FormatNumber(num / 1000) + "K";

if (num >= 10000)
return (num / 1000D).ToString("0.#") + "K";

return num.ToString("#,0");
}

Examples:

  • 1 => 1
  • 23 => 23
  • 136 => 136
  • 6968 => 6,968
  • 23067 => 23.1K
  • 133031 => 133K

Note that this will give strange values for numbers >= 108.

For example, 12345678 becomes 12.3KK.

String format numbers to millions, thousands with rounding

This should help, combined with one of the formatting techniques in the other questions you've linked to.

  internal long MaxThreeSignificantDigits(long x)
{
int i = (int)Math.Log10(x);
i = Math.Max(0, i - 2);
i = (int)Math.Pow(10, i);
return x / i * i;
}

EDIT:

OK, how about this?

 Console.WriteLine(SO30180672.FormatNumber(1));
Console.WriteLine(SO30180672.FormatNumber(12));
Console.WriteLine(SO30180672.FormatNumber(123));
Console.WriteLine(SO30180672.FormatNumber(1234));
Console.WriteLine(SO30180672.FormatNumber(12345));
Console.WriteLine(SO30180672.FormatNumber(123456));
Console.WriteLine(SO30180672.FormatNumber(1234567));
Console.WriteLine(SO30180672.FormatNumber(12345678));
Console.WriteLine(SO30180672.FormatNumber(123456789));

Following is partially copied from here: https://stackoverflow.com/a/23384710/253938

   internal class SO30180672
{
internal static string FormatNumber(long num)
{
num = MaxThreeSignificantDigits(num);

if (num >= 100000000)
return (num / 1000000D).ToString("0.#M");
if (num >= 1000000)
return (num / 1000000D).ToString("0.##M");
if (num >= 100000)
return (num / 1000D).ToString("0k");
if (num >= 100000)
return (num / 1000D).ToString("0.#k");
if (num >= 1000)
return (num / 1000D).ToString("0.##k");
return num.ToString("#,0");
}

internal static long MaxThreeSignificantDigits(long x)
{
int i = (int)Math.Log10(x);
i = Math.Max(0, i - 2);
i = (int)Math.Pow(10, i);
return x / i * i;
}
}

EDIT 2 - thank you very much to @Rhexis

   internal class SO30180672
{
internal static void RunTest()
{
Console.WriteLine(FormatNumber(1));
Console.WriteLine(FormatNumber(10));
Console.WriteLine(FormatNumber(100));
Console.WriteLine(FormatNumber(1000));
Console.WriteLine(FormatNumber(10000));
Console.WriteLine(FormatNumber(100000));
Console.WriteLine(FormatNumber(125000));
Console.WriteLine(FormatNumber(125900));
Console.WriteLine(FormatNumber(1000000));
Console.WriteLine(FormatNumber(1250000));
Console.WriteLine(FormatNumber(1258000));
Console.WriteLine(FormatNumber(10000000));
Console.WriteLine(FormatNumber(10500000));
Console.WriteLine(FormatNumber(100000000));
Console.WriteLine(FormatNumber(100100000));
}

private static string FormatNumber(long num)
{
// Ensure number has max 3 significant digits (no rounding up can happen)
long i = (long)Math.Pow(10, (int)Math.Max(0, Math.Log10(num) - 2));
num = num / i * i;

if (num >= 1000000000)
return (num / 1000000000D).ToString("0.##") + "B";
if (num >= 1000000)
return (num / 1000000D).ToString("0.##") + "M";
if (num >= 1000)
return (num / 1000D).ToString("0.##") + "K";

return num.ToString("#,0");
}
}

Format a number as 2.5K if a thousand or more, otherwise 900

Sounds like this should work for you:

function kFormatter(num) {    return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num)}    console.log(kFormatter(1200)); // 1.2kconsole.log(kFormatter(-1200)); // -1.2kconsole.log(kFormatter(900)); // 900console.log(kFormatter(-900)); // -900

Format numbers in thousands (K) in Excel

Custom format

[>=1000]#,##0,"K";0

will give you:

Sample Image

Note the comma between the zero and the "K". To display millions or billions, use two or three commas instead.

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

How to format numbers similar to Stack Overflow reputation format

Another approach that produces exactly the desired output:

function getRepString (rep) {
rep = rep+''; // coerce to string
if (rep < 1000) {
return rep; // return the same number
}
if (rep < 10000) { // place a comma between
return rep.charAt(0) + ',' + rep.substring(1);
}
// divide and format
return (rep/1000).toFixed(rep % 1000 != 0)+'k';
}

Check the output results here.

How to convert number into K thousands M million and B billion suffix in jsp

Adapting the answer from over here it should look something like

public static String withSuffix(long count) {
if (count < 1000) return "" + count;
int exp = (int) (Math.log(count) / Math.log(1000));
return String.format("%.1f %c",
count / Math.pow(1000, exp),
"kMGTPE".charAt(exp-1));
}

Test code:

for (long num : new long[] { 0, 27, 999, 1000, 110592,
28991029248L, 9223372036854775807L })
System.out.printf("%20d: %8s%n", num, withSuffix(num));

Output:

                   0:        0
27: 27
999: 999
1000: 1.0 k
110592: 110.6 k
28991029248: 29.0 G
9223372036854775807: 9.2 E

How to go about formatting 1200 to 1.2k in Android studio

This should do the trick

String numberString = "";
if (Math.abs(number / 1000000) > 1) {
numberString = (number / 1000000).toString() + "m";

} else if (Math.abs(number / 1000) > 1) {
numberString = (number / 1000).toString() + "k";

} else {
numberString = number.toString();

}

How to go about formatting 1200 to 1.2k in java

Here is a solution that works for any long value and that I find quite readable (the core logic is done in the bottom three lines of the format method).

It leverages TreeMap to find the appropriate suffix. It is surprisingly more efficient than a previous solution I wrote that was using arrays and was more difficult to read.

private static final NavigableMap<Long, String> suffixes = new TreeMap<> ();
static {
suffixes.put(1_000L, "k");
suffixes.put(1_000_000L, "M");
suffixes.put(1_000_000_000L, "G");
suffixes.put(1_000_000_000_000L, "T");
suffixes.put(1_000_000_000_000_000L, "P");
suffixes.put(1_000_000_000_000_000_000L, "E");
}

public static String format(long value) {
//Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1);
if (value < 0) return "-" + format(-value);
if (value < 1000) return Long.toString(value); //deal with easy case

Entry<Long, String> e = suffixes.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();

long truncated = value / (divideBy / 10); //the number part of the output times 10
boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}


Test code

public static void main(String args[]) {
long[] numbers = {0, 5, 999, 1_000, -5_821, 10_500, -101_800, 2_000_000, -7_800_000, 92_150_000, 123_200_000, 9_999_999, 999_999_999_999_999_999L, 1_230_000_000_000_000L, Long.MIN_VALUE, Long.MAX_VALUE};
String[] expected = {"0", "5", "999", "1k", "-5.8k", "10k", "-101k", "2M", "-7.8M", "92M", "123M", "9.9M", "999P", "1.2P", "-9.2E", "9.2E"};
for (int i = 0; i < numbers.length; i++) {
long n = numbers[i];
String formatted = format(n);
System.out.println(n + " => " + formatted);
if (!formatted.equals(expected[i])) throw new AssertionError("Expected: " + expected[i] + " but found: " + formatted);
}
}


Related Topics



Leave a reply



Submit