Convert Decimal To String With Trailing Zeroes [ C# ]

convert decimal to string
It is very tedious to always convert string to decimal and decimal to string when we deal with objects in C#. And it is quite clumsy if your manager ask you to show a value with trailing zeroes(I really hate it, but not him).
So there may be situations when we want to show the decimal values as string with trailing zeroes to customer/ or UI as :

Let say we want to show 3 decimal places after precision for every number and number should look like below:

  • 1.30 >> 1.300
  • 1.1 >> 1.100
  • 1.00 >> 1
  • 1.01 >> 1.010

String.Format is the one method that really going to help us achieve this using the code below. So if you really wanna know about string format function check it out msdn reference for this.

And lets talk some code now:

        // pass a decimal number
		decimal Number = 1.12m;
		
		// define a scale to show after decimal point
		int scale = 10;
		
		//create a precision scale using scale defined
		string precisionScale = new String('0', scale);
            
		//define string format using precision scale
		string format = "{0:0." + precisionScale + "}";

        
		//format the number as string
		var numberAsString = string.Format(format, Number);

        //if number has zeroes after decimal point, return number itself    
		if (numberAsString.EndsWith(precisionScale))
        {
            //returning the number without zeroes, if it has all zeroes trailing after precision 
			Console.WriteLine(((int)Number).ToString());
        }
        else
		{
             Console.WriteLine(numberAsString);
		}

And if you got a different situation for doing this, why don’t you play with this fiddle

Cheers!!

Advertisements

Say something : I accept all the "Humer&Critic"

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s