Make a code that brings values like this(1K, 1M or 2G)

Asked

Viewed 127 times

3

My rule is: If a figure is in the thousands, I must present so:

1564 = 1K

345,786 = 345K

2345 = 2K

The same goes for millions and so on. Well, the question is how to get only the values before the first point and etc...

3 answers

6

Something like:

List<string> siglas = new List<string>() {
    "K", // Kilo
    "M", // Mega
    "G", // Giga
    "T", // Tera
    "Y"  // Yota
};

long numero = 102314124; // ou qualquer outro número
string resultado = numero.ToString();       
while (numero > 1000 && siglas.Count > 0) {
    numero /= 1000;
    resultado = numero + siglas[0];
    siglas.RemoveAt(0);
}

At the end of the loop, the string resultado have what you want. Note that the loop ends abruptly if you run out of more acronyms. You can add more acronyms if you wish.

  • Very good! As a hint I would say that the ToString is "left over" there, because the concatenation already converts to string. Another small detail is that the number 10231204124 does not fit in a int and that it would be better to initialize result with a string empty so I can use it right after :p If you don’t mind I can edit xD

  • Renan, keep coming to the decimal part. The rule as I said, would be, if the number is 38890 would run 38K, but the part of removing the decimal I see here.

  • @LINQ at will :)

2

You can do something like this:

public static void Main()
{
    long[] numeros = {
        1, 10, 100,
        1000, 10000, 1000000, 125000, 125900,
        1000000, 1250000, 1258000,
        10000000, 10500000, 100000000, 100100000,
        1000000000
    };

    foreach (var numero in numeros)
    {
        Console.WriteLine(FormataNumero(numero));
    }
}

public static string FormataNumero(long numero)
{
    // Certifica-se de que o número tenha no máximo 3 dígitos significativos
    // (nenhum arredondamento pode acontecer)
    var i = (long)Math.Pow(10, (int)Math.Max(0, Math.Log10(numero) - 2));
    numero = numero / i * i;

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

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

Credits to that answer in Soen

See working on dotnetfiddle here

2


If you want a result without rounding you can use Regex:

using System;
using System.Text.RegularExpressions; //não esqueça desse using

public class Program
{
    public static void Main()
    {
        string valor = "1.564"; //valor declarado

        string strRegex = "(\\.*)"; //remove os pontos

        valor = Regex.Replace(valor, strRegex, "");

        strRegex = "(\\,\\d{2})"; //remove a parte decimal

        valor = Regex.Replace(valor, strRegex, "");

        strRegex = "\\b(\\d{1,3})\\d{3}\\b"; //regex para verificar se o numero esta na casa de milhar

        if(Regex.Matches(valor, strRegex).Count > 0){
            valor = Regex.Replace(valor, strRegex, "$1K");
            Console.WriteLine(valor);
        }
        strRegex = "\\b(\\d{1,3})\\d{6}\\b"; //regex para verificar se o numero esta na casa de milhão
        if(Regex.Matches(valor, strRegex).Count > 0){
            valor = Regex.Replace(valor, strRegex, "$1M");
            Console.WriteLine(valor);
        }
        strRegex = "\\b(\\d{1,3})\\d{9}\\b"; //etc...
        if(Regex.Matches(valor, strRegex).Count > 0){
            valor = Regex.Replace(valor, strRegex, "$1T");
            Console.WriteLine(valor);
        }
        strRegex = "\\b(\\d{1,3})\\d{12}\\b";
        if(Regex.Matches(valor, strRegex).Count > 0){
            valor = Regex.Replace(valor, strRegex, "$1Q");
            Console.WriteLine(valor);
        }
    }
}

Here is a test of the functioning on dotnetfiddle

  • If the number has decimal part it mounts NK,35 for example. But I see here

  • I’ll edit it to work the way you want to.

  • @pnet done. check the dotnetfiddle and see if the result satisfies you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.