Eliminar ceros finales


Tengo algunos campos devueltos por una colección como

2.4200
2.0044
2.0000

Quiero resultados como

2.42
2.0044
2

Probé con String.Format, pero devuelve 2.0000 y ajustándolo a N0 redondea los otros valores también.

Author: Stijn, 2010-12-24

15 answers

No Es tan simple como esto, si la entrada ES una cadena? Puedes usar uno de estos:

string.Format("{0:G29}", decimal.Parse("2.0044"))

decimal.Parse("2.0044").ToString("G29")

2.0m.ToString("G29")

Esto debería funcionar para todas las entradas.

Actualizar Echa un vistazo a los Formatos Numéricos estándar He tenido que establecer explícitamente el especificador de precisión a 29 como los documentos indican claramente:

Sin embargo, si el número es un decimal y se omite el especificador de precisión, siempre se usa la notación de punto fijo y los ceros finales son conservados

Actualización Konrad señaló en los comentarios:

Tenga cuidado con valores como 0.000001. El formato G29 los presentará de la manera más corta posible, por lo que cambiará a la notación exponencial. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) dará "1E-08" como resultado.

 135
Author: Dog Ears,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:02

Me encontré con el mismo problema, pero en un caso en el que no tengo el control de la salida a la cadena, que fue atendido por una biblioteca. Después de examinar los detalles en la implementación del tipo decimal (véase http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx ), Se me ocurrió un buen truco (aquí como un método de extensión):

public static decimal Normalize(this decimal value)
{
    return value/1.000000000000000000000000000000000m;
}

La parte exponente del decimal se reduce a lo que se necesita. Llamando a toString () en el decimal de salida escribirá el número sin ningún 0 final. Por ejemplo,

1.200m.Normalize().ToString();
 164
Author: Thomas Materna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-03 19:22:30

En mi opinión es más seguro usar Cadenas de Formato numérico personalizadas.

decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
 74
Author: Michał Powaga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-22 09:00:06

Utilizo este código para evitar la notación científica "G29":

public static string DecimalToString(decimal dec)
{
    string strdec = dec.ToString(CultureInfo.InvariantCulture);
    return strdec.Contains(".") ? strdec.TrimEnd('0').TrimEnd('.') : strdec;
}
 22
Author: x7iBiT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-28 01:43:21

Encontré una solución elegante de http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/

Básicamente

Decimal v = 2.4200 M;

V. toString("#.######"); // Devolverá 2.42. El número de # es cuántos dígitos decimales admite.

 9
Author: DHornpout,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 02:38:45

Use el símbolo hash (#) para mostrar solo los 0 finales cuando sea necesario. Vea las pruebas a continuación.

decimal num1 = 13.1534545765;
decimal num2 = 49.100145;
decimal num3 = 30.000235;

num1.ToString("0.##");       //13.15%
num2.ToString("0.##");       //49.1%
num3.ToString("0.##");       //30%
 8
Author: Fizzix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-30 03:49:15

Esto hace exactamente lo que quieres:

Si su valor inicial es decimal:

decimal source = 2.4200m;
string output = ((double)source).ToString();

Si su valor inicial es string:

string source = "2.4200";
string output = double.Parse(source).ToString();

Y debería costar un rendimiento mínimo.

 3
Author: Shimmy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-05 02:28:54

Depende de lo que su número representa y cómo desea administrar los valores: ¿es una moneda, necesita redondeo o truncamiento, necesita este redondeo solo para mostrar?

Si para la visualización considerar formatear los números son x. toString("")

Http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx y

Http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Si es solo redondeo, use Matemáticas.Ronda de sobrecarga que requiere una sobrecarga de punto medio

Http://msdn.microsoft.com/en-us/library/ms131274.aspx )

Si obtiene su valor de una base de datos, considere el casting en lugar de la conversión: valor doble = (decimal)MyRecord ["ColumnName"];

 1
Author: florin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-24 11:08:22

Un enfoque de muy bajo nivel, pero creo que esta sería la forma más eficaz al usar solo cálculos enteros rápidos (y sin análisis lento de cadenas y métodos sensibles a la cultura):

public static decimal Normalize(this decimal d)
{
    int[] bits = decimal.GetBits(d);

    int sign = bits[3] & (1 << 31);
    int exp = (bits[3] >> 16) & 0x1f;

    uint a = (uint)bits[2]; // Top bits
    uint b = (uint)bits[1]; // Middle bits
    uint c = (uint)bits[0]; // Bottom bits

    while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
    {
        uint r;
        a = DivideBy10((uint)0, a, out r);
        b = DivideBy10(r, b, out r);
        c = DivideBy10(r, c, out r);
        exp--;
    }

    bits[0] = (int)c;
    bits[1] = (int)b;
    bits[2] = (int)a;
    bits[3] = (exp << 16) | sign;
    return new decimal(bits);
}

private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
    ulong total = highBits;
    total <<= 32;
    total = total | (ulong)lowBits;

    remainder = (uint)(total % 10L);
    return (uint)(total / 10L);
}
 1
Author: Bigjim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-17 23:47:09

La respuesta muy simple es usar TrimEnd(). Aquí está el resultado,

double value = 1.00;
string output = value.ToString().TrimEnd('0');

La Salida es 1 Si mi valor es 1.01 entonces mi salida será 1.01

 0
Author: Raj De Inno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-22 10:12:12

Se podría usar el siguiente código para no usar el tipo de cadena:

int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
    decimalResult = decimalResult / 10;
}
return decimalResult;

Devuelve 789.5

 0
Author: Raul Minon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-13 14:30:27

Puede simplemente establecer como:

decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));
 -1
Author: Danilo Ferreira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-29 17:45:13

Truncar ceros al final es muy fácil, resolver con un cast dúplex:

        decimal mydecimal = decimal.Parse("1,45000000"); //(I)
        decimal truncate = (decimal)(double)mydecimal;   //(II)

(I) Par> Analizar el valor decimal de cualquier fuente de cadena.

(II) First> Primero: Cast para duplicar esto elimina los ceros finales. Segundo: Otro cast a decimal porque no existe conversión implícita de decimal a doble y viceversa)

 -2
Author: amedriveroperez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-12 19:45:23

Prueba este código:

string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
 -2
Author: Raju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-15 05:53:58

Intenta así

string s = "2.4200";

s = s.TrimStart('0').TrimEnd('0', '.');

Y luego convertir eso en flotador

 -10
Author: Singleton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-24 10:54:41