ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

RemoveTraillingZeros

Remove trailling zeros from a decimal value

Source

public static decimal RemoveTraillingZeros(this decimal number)
{
    return decimal.Parse(number.ToString("0.#######", new System.Globalization.CultureInfo("en-US")), new System.Globalization.CultureInfo("en-US"));
}

Example

// d has been set from a numeric column in a database with the value 23.000000 

Debug.WriteLine(string.Format("Value is {0}", d); // outputs Value is 23.000000
Debug.WriteLine(string.Format("Value is {0}", d.RemoveTraillingZeros()); // outputs Value is 23

// d has been set from a numeric column in a database with the value 23.040000 

Debug.WriteLine(string.Format("Value is {0}", d); // outputs Value is 23.040000
Debug.WriteLine(string.Format("Value is {0}", d.RemoveTraillingZeros()); // outputs Value is 23.04

Author: Alberto Silva

Submitted on: 12 jul. 2018

Language: C#

Type: System.Decimal

Views: 4581